2017-02-17 106 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

相關問題