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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With