7

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.

Sophie Alpert
  • 139,698
  • 36
  • 220
  • 238

2 Answers2

8

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.)

Corbin
  • 33,060
  • 6
  • 68
  • 78
4

With the first this is the same in the function as it is in the scope when it is called, for the second this would refer to the window object.

Musa
  • 96,336
  • 17
  • 118
  • 137