2017-02-17 242 views
-1

这涉及到这样一个问题: Is it possible to spread the input array into arguments?为什么我不能调用function.apply?

我猜想,鉴于这行代码:

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 

这到底是怎么发生的?

+0

所以......相关性? –

回答

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) 

这是正确的。

1

我得到它的工作

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

你有它的工作,但没有解释“这里发生了什么??” – nnnnnn

相关问题