[英]Why does this result?
I recently watched a video where the teacher demonstrated that the javascript code 我最近看了一个视频,其中的老师演示了JavaScript代码
alert.call.apply(function(a) {return a}, [1,2])
results always in "2". 结果始终为“ 2”。 So here is my question: Why?? 所以这是我的问题:为什么?
I could not find any explination why this result is returned. 我找不到任何解释为什么返回此结果。
This code is just too clever! 这段代码太聪明了! But wait, the following code will produce the same result: 但是,下面的代码将产生相同的结果:
console.log.call.apply(function(a) {return a}, [1,2])
Here is what's happening: apply()
's first parameter is a ' this
', the second is a list of argument. 这是发生了什么: apply()
的第一个参数是' this
',第二个是参数列表。 It then calls the function console.log.call
with those parameters, which logically is equivalent to: 然后,使用这些参数调用功能console.log.call
,这些参数在逻辑上等效于:
(function(a) {return a}).call(1,2)
This code produces the same result and is a little bit easier to understand - we are using call()
on the unnamed function. 这段代码产生相同的结果,并且更容易理解-我们在未命名函数上使用call()
。 call()
's parameters are a ' this
' object followed by arguments. call()
的参数是一个“ this
”对象,后跟参数。 In this case ' this
' is 1
, and the argument is 2
, so the function gets called with a
assigned to 2
(the 1
is not used in the function which is unbound). 在这种情况下,“ this
”为1
,参数为2
,因此该函数a
赋值为2
的方式调用(未绑定的函数中未使用1
)。 So this will always return 2
, since it is simply returning the second item in the list. 因此,它将始终返回2
,因为它只是返回列表中的第二项。
But what is the role of alert
, and why can we substitute any function name there? 但是alert
的作用是什么,为什么我们可以在那里替换任何函数名称? Well, it seems that there is a single call()
function that is shared between all prototypes. 好吧,似乎只有一个call()
函数在所有原型之间共享。 You can verify that hypothesis by running 您可以通过运行来验证该假设
alert.call === console.log.call
true
So it doesn't matter if we use alert
, console.log
, or nothing, we are always using the same call()
function. 因此,无论我们使用alert
, console.log
还是什么都不用,我们始终使用相同的call()
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.