IIFE: var vs this - is there any difference?

235 views Asked by At

Is there any difference between this and var in immediately invoced function expressions(IIFE)?

(function(){
    var foo = 0;
    this.bar = 0;
})();
3

There are 3 answers

0
Omri Aharon On

If your code is executed in the global context, then two options:

  1. You're in use strict mode, and in which case this points to nothing (null or undefined) and then you'll see an exception.

  2. You're not in use strict mode and then this points to the window, in which case you'll set bar as a global variable.

var keeps the variable local (same scope it is run in) and will not be exposed to outside calls of the IIFE.

0
Dave Newton On

Of course there is.

  • foo is a variable scoped within the IIFE
  • bar will be evaluated against whatever this is bound to in the execution context.
0
Matías Fidemraizer On

var is a local-scoped variable. That is, it won't be available outside the IIFE.

In the other hand, this.bar adds a property to current object. In your case it's window.

I would recommend the following solution if you want to export variables, functions or any member to other scope:

   var MyModule = (function(exports){
        var foo = 0;
        exports.bar = 0;

        return exports;
    })(MyModule || {});

Above code is a simple implementation of module pattern.

In the other hand, if you want to define what's this inside the IIFE, you can invoke it using call:

   // You don't need "exports" anymore
   // since "this" works the same way
   var MyModule = (function(){
        var foo = 0;
        this.bar = 0;

        return this;
    }).call(MyModule || {});

At the end of the day, the value of this depends on how a function is called. If you don't provide the meaning of this with call, bind or apply, it will depend on how the function is called. For example, if a function is part of an object, then this will be the object who owns the function:

var obj = {
    doStuff: function() {
         // "this" is "obj" by default
    }
};