JavaScript Independent Functions - What's the Difference?

I am very familiar with the self-learning features of working with jQuery.

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

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

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

Does it achieve the same thing? Will the next two lines of code do the same?

 (function($) { /* do stuff */ })(jQuery); (function($) { /* do stuff */ }).call(jQuery); 
+7
source share
4 answers

The first form is passed in the parameter, and the second form sets what 'this' means 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] 

See Function.prototype.call and Function.prototype.apply for more information.

Here you can use the call technique:

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

Without setting this through call() , the self-service function is called in the global area (window), not the current object.

+12
source

In their case:

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

... they are sure that the function is called with a specific value for this (for example, this inside the function will be the same as this outside the function).

In your case:

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

... this inside your function will be a global object because you called it without doing anything that sets this , and therefore this defaults to the global object ( window , on browers).

In JavaScript, this completely determined by how the function is called. There are two main ways:

  • Calling a function as part of an expression that extracts it from an object property, for example

     obj.foo(); // Or `obj["foo"](); 

    In this case, as part of calling foo , this will refer to obj .

  • Calling a function through the built-in call or apply :

     var obj = {name: "Fred"}; function foo(salutation, punctuation) { alert(salutation + " " + this.name + punctuation); } foo.call(obj, "Hi", "!"); // alerts "Hi Fred!" foo.apply(obj, ["Hi", "!"]); // Also alerts "Hi Fred!" 

    The only difference between call and apply is how you specify the arguments to pass to the function you are calling: With call you simply specify them as discrete arguments corresponding to the required this value; with apply , you supply them as an array.

+3
source

The first passes jQuery as the $ parameter. The second makes jQuery the variable 'this' inside the function.

+1
source

.call places the function in the closing area.

So, if you did this:

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

$ will be undefined

-2
source

All Articles