[英]Difference between (func)() and (func).call(window)
I am studying how to create some plugins using angularjs
and in some of them I have faced this: 我正在研究如何使用
angularjs
创建一些插件,其中一些我已经遇到了这个问题:
(function() {
'use strict'
//code...
}).call(window);
what is the difference from just using a self-invoking function like that below? 与仅使用下面的自调用功能有什么区别?
(function() {
'use strict'
//code...
})();
The two invocations will have different this
values. 这两个调用将具有不同的
this
值。
This code 这段代码
(function() {
'use strict'
console.log(this)
})();
will log undefined
because direct non-method invocations of strict-mode functions use a this
value of undefined
. 将记录
undefined
因为严格模式函数的直接非方法调用使用this
值undefined
。
This code 这段代码
(function() {
'use strict'
console.log(this)
}).call(window);
will log window
since the first argument to call
is used to supply this
to the function being invoked. 将登录
window
,因为第一个参数call
用于提供this
到被调用的函数。
If I had to guess, I'd say this is being done to mimic the non-strict behavior of using window
(instead of undefined
) for this
of a bare non-method invocation. 如果我猜的话,我会说这么做是模仿使用的非严格的行为
window
(而不是undefined
),用于this
裸非方法调用。 Simply use window
if you mean window
. 只需使用
window
,如果你的意思是window
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.