(func)() 和 (func).call(window) 之间的区别

Difference between (func)() and (func).call(window)

我正在研究如何使用 angularjs 创建一些插件,其中一些我遇到过这个问题:

(function() {
    'use strict'
    //code...
}).call(window);

与仅使用像下面这样的自调用函数有什么区别?

(function() {
    'use strict'
    //code...
})();

这两个调用将有不同的 this 值。

这个代码

(function() {
    'use strict'
    console.log(this)
})();

将记录 undefined 因为严格模式函数的直接非方法调用使用 thisundefined.

这个代码

(function() {
    'use strict'
    console.log(this)
}).call(window);

将记录 window,因为 call 的第一个参数用于向被调用的函数提供 this

如果非要我猜的话,我会说这样做是为了模仿对 this 使用 window(而不是 undefined)的非严格行为裸非方法调用。如果您的意思是 window,只需使用 window