I was looking at the code for the underscore.js library (jQuery does the same thing) and just wanted some clarification on why the window object is getting passed into the self executing function.
For example:
(function() { //Line 6
var root = this; //Line 12
//Bunch of code
}).call(this); //Very Bottom
Since this is global, why is it being passed into the function? Wouldn’t the following work as well? What issues would arrise doing it this way?
(function() {
var root = this;
//Bunch of code
}).call();
I suspect the reason is ECMAScript 5 strict mode.
In non-strict mode, this IIFE
logs the
windowobject (or theglobalobject, if you’re on a node.js server), because the global object is supplied asthisto functions that don’t run as a method of an object.Compare that result to
In strict mode, the
thisof a bare-invoked function is undefined. Therefore, the Underscore authors usecallto supply an explicitthisto the anonymous function so that it is standardized across strict and non-strict mode. Simply invoking the function (as I did in my examples) or using.call()leads to an inconsistency that can be solved with.call(this).