Search code examples
javascriptangularjsself-invoking-function

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


I came across this code in one of our online AngularJS apps, and was wondering what this does. Is it different than just calling a immediately self invoking function with parenthesis.

(function() {

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

vs

(function() {

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

Is there any benefits of calling one over the other, or is it merely coding preference?


Solution

  • They're very different. The first uses whatever the current this is (at global scope, this is a reference to the global object; in other scopes, it could be just about anything). The second will use the default this, which is a reference to the global object in loose mode but undefined in strict mode.

    Gratuitous example :-) :

    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;
    }