Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between IIFE and call

Is there a difference between:

(function(){

}).call(this);

and

(function(){

})();

or

var MODULE = {};
(function(){
    this.hello = 'world'
}).call(MODULE);

and

var MODULE = {};
(function(m){
    m.hello = 'world'
})(MODULE);

I often see the first case in compiled javascript. They both would create a scope and do their namespacing job well.

Is there any difference or is it just a matter of taste.

Edit: And why would compiled javascript would use call over IIFE?

like image 971
Jonathan de M. Avatar asked Jul 12 '13 02:07

Jonathan de M.


1 Answers

(function(){

}).call(this);

calls the anonymous function where the this inside the function will point to the object referred by this when the call was made.

(function(){

})();

calls the anonymous function where the this inside the function will point to the global object (or undefined in strict mode)

Demo: Fiddle

like image 58
Arun P Johny Avatar answered Nov 05 '22 09:11

Arun P Johny