Is there any difference between this and var in immediately invoced function expressions(IIFE)?
(function(){
var foo = 0;
this.bar = 0;
})();
Is there any difference between this and var in immediately invoced function expressions(IIFE)?
(function(){
var foo = 0;
this.bar = 0;
})();
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
}
};
If your code is executed in the global context, then two options:
You're in
use strictmode, and in which casethispoints to nothing (null or undefined) and then you'll see an exception.You're not in
use strictmode and thenthispoints to the window, in which case you'll setbaras a global variable.varkeeps the variable local (same scope it is run in) and will not be exposed to outside calls of the IIFE.