.call(this) 和 () 在立即自调用函数上的区别

Differences between .call(this) and () on a immediately self invoking function

我在我们的一个在线 AngularJS 应用程序中看到了这段代码,并且想知道它的作用。它与仅调用带括号的立即自调用函数不同吗?

(function() {

}).call(this); // What was in TFS

(function() {

})(); // Are these the same?

调用一个比另一个有什么好处,还是仅仅是编码偏好?

它们非常不同。第一个使用当前 this 是什么(在全局范围内,this 是对全局对象的引用;在其他范围内,它可以是任何东西)。第二个将使用默认值 this,它在松散模式下是对全局对象的引用,但在严格模式下是 undefined

免费示例:-) :

console.log("At global scope:");
(function() {
  console.log(this === window); // true
}).call(this); // What was in TFS
(function() {
  console.log(this === window); // true
})();
(function() {
  "use strict";
  console.log(this === window); // false (this === undefined)
})();

console.log("Not at global scope:");
(function() {
  (function() {
    console.log(this === window); // false
  }).call(this); // What was in TFS
  (function() {
    console.log(this === window); // true
  })();
}).call({});// Using something other than the default
.as-console-wrapper {
  max-height: 100% !important;
}