1

Two methods I've seen (I know there are more) of using an IIFE:

(function(){
    console.log(this);
}).call(this);

(function(){
    console.log(this);
})();

Is there any reason to use .call(this) on the first one? Won't (); yield the same context within the function?

benhowdle89
  • 36,900
  • 69
  • 202
  • 331
  • related: [Why use the javascript function wrapper “.call(this)”](http://stackoverflow.com/q/4542942/1048572) – Bergi Sep 12 '14 at 14:43

1 Answers1

4

That depends on where the code is executed.

.call(this) explicitly sets the this to the object you pass to .call. Only using (); will set this to window (or to undefined in strict mode).

If the code is executed in global scope it will be the same. If not, then you will get different results if this does not refer to window (or is undefined).

Example:

var obj = {
   foo: function() {
       (function(){
           console.log(this); // this === obj
       }).call(this); // this === obj

       (function(){
           console.log(this); // this === window
       })();
   }
};

obj.foo();

More information about this on MDN

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143