Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IIFE and window object?

IIFE which need to access non-overridden window object - can be seen as:

something like (jQuery example):

$(function (global) {
  // do something with global
})( window );

But sometimes I also see this (underscore.js):

(function() {
  var global= this;
  // do something with global
}).call(this);

Question 1: is there any difference? If so, when should I use each?

Question 2: this inside IIFE is window. Why is it necessary to "send" window/call(this)? (jQuery isn't using strict mode imho)

NB

It looks like jQuery (since 1.11.0) has also adopted this pattern:

(function (global, factory)
{
   //....

}(typeof window !== "undefined" ? window : this, function (window, noGlobal)
{
   //...
});
like image 463
Royi Namir Avatar asked Mar 09 '14 10:03

Royi Namir


People also ask

What does IIFE mean in JavaScript?

IIFE An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The name IIFE is promoted by Ben Alman in his blog. (function () { statements })();

How to use arrow functions to define IIFEs?

Note that you can use an arrow function to define an IIFE: ( () => { //... }) (); By placing functions and variables inside an immediately invoked function expression, you can avoid polluting them to the global object: ( function() { var counter = 0 ; function add(a, b) { return a + b; } console .log (add ( 10, 20 )); // 30 } ());

Does immediately running a function make it an IIFE?

The first I in IIFE stands for immediately but it does not signifies that immediately running a function makes the function an IIFE. I am also intrigued by the use case everybody uses in their tutorials - If you want to write a function and call it immediately. Did you ever come across such a scenario? Functions are there for a purpose.

Is it possible to change the scope of a function inside IIFE?

The statement is factually correct BUT remember that every IIFE is just another function. So as a result anything declared inside an IIFE will be available only inside the function body and will not be visible outside thereby preventing the outside scope to get modified. There is nothing special here.


Video Answer


1 Answers

(function() {
  var win = this;
  // do something with win
  }).call(this);

Underscore is a javascript library not a DOM library,therefore it should not use window anywhere,since javascript is not the DOM and window is a DOM api

Underscore isnt tied to the DOM with this approach. Trying to call window in nodejs or rhino is not going to work and doesnt make any sense.

EDIT :

call sets the context of the function to this(global or window) , so no need to pass anything as an argument.

like image 179
mpm Avatar answered Sep 27 '22 22:09

mpm