Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping a file with (function() { … }).call(this) versus a call with simply () [duplicate]

Tags:

javascript

The backbone.js source code uses a function wrapper like this:

(function(){
    ...
}).call(this);

as seen at http://backbonejs.org/docs/backbone.html#section-185.

Much more often, I've seen the following used instead:

(function(){
    ...
})();

When does the behavior of these two differ? I was under the impression that they were equivalent, but I assume that there must be a difference given that Backbone uses .call(this) instead of the shorter alternative.

like image 553
Sophie Alpert Avatar asked Jul 20 '12 22:07

Sophie Alpert


1 Answers

In the first example, this inside of the function will be the this from the calling scope.

In the second example, this will be window.

(As noted by Šime Vidas, it's undefined in strict mode, rather than window.)

like image 180
Corbin Avatar answered Sep 19 '22 21:09

Corbin