[英]Why can I not call a function.apply?
This is related to this question: Is it possible to spread the input array into arguments? 这与以下问题有关: 是否可以将输入数组扩展为参数?
I'm assuming that given this line of code: 我假设给出以下代码:
Promise.all(array).then(foo)
Promise.all
uses Function.call
, to invoke foo
, Promise.all
使用Function.call
来调用foo
,
foo.call(foo, arrayValues)
I would like to modify foo
into a foo.apply
function such that calling it with an array of values splits it into regular arguments. 我想将foo
修改为foo.apply
函数,以便使用值数组调用它可以将其拆分为常规参数。
Here is my train of thought.... 这是我的思路。
Assuming I have this function 假设我有这个功能
function test(a,b,c){
console.log(a,b,c)
}
I can call this function using both call
and apply
我可以同时使用call
和apply
来调用此函数
test.call(null,1,2,3)
>> 1 2 3
test.apply(null,[1,2,3])
>> 1 2 3
So far so good, this also works... 到目前为止,这还行得通...
test.call.apply(test,[null,1,2,3])
>> 1 2 3
However I cannot get this to work 但是我不能让它工作
test.apply.call(test,[null,1,2,3])
>> undefined undefined undefined
What is happening here?? 这是怎么回事?
I got it to work 我上班了
test.apply.call(test,null,[1,2,3])
>> 1 2 3
test.apply.call(test,[null,1,2,3])
equals to 等于
test.apply([null,1,2,3])
equals to 等于
test()
So you got undefined as output. 因此您未定义为输出。
test.apply.call(test,null,[1,2,3])
equals to 等于
test.apply(null,[1,2,3])
equals to 等于
test(1,2,3)
This is right. 这是对的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.