Reason behind this self invoking anonymous function variant

By default, invoking a function like (function(){/*...*/})() will set the value of this in the function to window (in a browser) irrespective of whatever the value of this may be in the enclosing context where the function was created.

Using call allows you to manually set the value of this to whatever you want. In this case, it is setting it to whatever the value of this is in the enclosing context.

Take this example:

var obj = {
    foo:'bar'
};

(function() {
    alert( this.foo ); // "bar"
}).call( obj );

http://jsfiddle.net/LWFAp/

You can see that we were able to manually set the value of this to the object referenced by the obj variable.

Leave a Comment