Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is .call(this) used instead of parenthesis [duplicate]

Tags:

javascript

Is there a particular reason why i often encounter:

(function() {
  console.log("Hello");
}).call(this);

instead of:

(function() {
  console.log("Hello");
})();

It should have the same effect when passing this to call or not?

There seems to be some performance difference: http://jsperf.com/call-vs-parenthesis.

like image 607
Nick Russler Avatar asked Dec 10 '13 18:12

Nick Russler


Video Answer


2 Answers

Presumably the code within that function uses this (where you just have console.log). In the version with call, this within the function is the same as this outside it. Without call, this inside the function is either the global object (loose mode) or undefined (strict mode).

If you're not using this within the function, there's no reason to be doing the call version, and I would lean toward not doing so because it's additional unnecessary complexity (and apparently a very very small performance cost).

like image 123
T.J. Crowder Avatar answered Oct 02 '22 02:10

T.J. Crowder


The addition of .call(this) is important, it changes the context of the function enclosure, meaning that the this keyword will refer to the same this as the outer function enclosure.

In your particular code it doesn't make any difference because inside your function you do not refer to this at all.

this.a = 123;
(function() {
   console.log(this.a); // always 123 regardless of scope
}).call(this);

That is significant assuming that this refers to something other than the window object. If this is already pointing to the window, then adding .call(this) makes no difference, since without it, by default the this will go to the window.

like image 33
codefactor Avatar answered Oct 02 '22 01:10

codefactor