IIFE and window object?

IIFE , which needs to access the non-overlapping 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 a window. why did you need to "send" window / "call (this)"? (jQuery does not use imho strict mode)

N.B.

It seems that jQuery since 1.11.0 also added this pattern:

 (function (global, factory) { //.... }(typeof window !== "undefined" ? window : this, function (window, noGlobal) { //... }); 
+6
source share
1 answer
 (function() { var win = this; // do something with win }).call(this); 

Underscore is a javascript library, not a DOM library, so it should not be used anywhere since javascript is not a DOM and the window is a DOM api

The underline does not bind to the DOM with this approach. Attempting to call a window in nodejs or rhino will not work and makes no sense.

EDIT:

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

+3
source

All Articles