Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Self Executing Functions - What's the Difference?

I am very familiar with self executing functions from working with jQuery.

(function($) { /* do stuff */ })(jQuery);

Today I was reading the backbone.js source and noticed that they do this:

(function() { /* do stuff */ }).call(this);

Is this achieving the same thing? Would the following 2 lines of code do the same thing?

(function($) { /* do stuff */ })(jQuery);
(function($) { /* do stuff */ }).call(jQuery);
like image 306
modernzombie Avatar asked Nov 22 '11 17:11

modernzombie


1 Answers

The first form is passing in a parameter, while the second form is setting what 'this' refers to inside the executing function. They are different.

(function(x){ console.log(this,x); })( jQuery );
//--> [window object]
//--> [jQuery object]

(function(x){ console.log(this,x); }).call( jQuery );
//--> [jQuery object]
//--> undefined

(function(x){ console.log(this,x); }).call( jQuery, jQuery );
//--> [jQuery object]
//--> [jQuery object]

For more information, see Function.prototype.call and Function.prototype.apply.

Here's a case where you might want to use the call technique:

v = 'oh noes!'
var o = {
  v : 42,
  f : function(){
    console.log(this.v);
    (function(){ console.log(this.v) })();
  }
};
o.f();
// --> 42
// --> 'oh noes!'

Without setting the value of this via call(), the self-calling function is invoked in the scope of the Global (window), not the current object.

like image 124
Phrogz Avatar answered Sep 24 '22 09:09

Phrogz