Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you need to pass in arguments to a self executing function in javascript if the variable is global?

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();
like image 650
KingKongFrog Avatar asked Dec 13 '12 17:12

KingKongFrog


1 Answers

I suspect the reason is ECMAScript 5 strict mode.

In non-strict mode, this IIFE

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

logs the window object (or the global object, if you're on a node.js server), because the global object is supplied as this to functions that don't run as a method of an object.

Compare that result to

"use strict";
(function() {
   console.log(this); // undefined
})();

In strict mode, the this of a bare-invoked function is undefined. Therefore, the Underscore authors use call to supply an explicit this to 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).

like image 195
apsillers Avatar answered Oct 22 '22 09:10

apsillers