【问题标题】:Why can I not call a function.apply?为什么我不能调用 function.apply?
【发布时间】:2017-02-17 20:24:33
【问题描述】:

这与这个问题有关: Is it possible to spread the input array into arguments?

我假设给定这行代码:

Promise.all(array).then(foo)

Promise.all 使用Function.call,调用foo

foo.call(foo, arrayValues)

我想将foo 修改为foo.apply 函数,以便使用值数组调用它会将其拆分为常规参数。

这是我的思路......

假设我有这个功能

function test(a,b,c){
    console.log(a,b,c)
}

我可以同时使用callapply 调用这个函数

test.call(null,1,2,3)
>> 1 2 3
test.apply(null,[1,2,3])
>> 1 2 3

到目前为止一切顺利,这也有效......

test.call.apply(test,[null,1,2,3])
>> 1 2 3

但是我不能让它工作

test.apply.call(test,[null,1,2,3])
>> undefined undefined undefined

这里发生了什么??

【问题讨论】:

  • 所以...相关性?

标签: javascript


【解决方案1】:
test.apply.call(test,[null,1,2,3])

等于

test.apply([null,1,2,3])

等于

test()

所以你得到了未定义的输出。


test.apply.call(test,null,[1,2,3])

等于

test.apply(null,[1,2,3])

等于

test(1,2,3)

这是对的。

【讨论】:

    【解决方案2】:

    我已经开始工作了

    test.apply.call(test,null,[1,2,3])
    >> 1 2 3
    

    【讨论】:

    • 你让它工作了,但没有解释“这里发生了什么?”
    猜你喜欢
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多