Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between x.f.call(x, ...) and x.f(...)?

Tags:

javascript

I'm looking at some code that looks like

this.f.call(this);

Or in some other cases

this.someObj.f.call(this.someObj);

Is there any difference between these and

this.f();
this.someObj.f();

Are there any circumstances where the behavior would be different? (For example, is the behavior different if this or someObj is null or isn't actually an object, or f isn't actually a function? I can't think of a way where one would throw an exception and the other wouldn't, but maybe I'm missing something...)

EDIT: To clarify: yes, I know that .call can be used to specify the this value seen by the function, and it can be useful in cases where you can't use the obj.f() syntax (because f isn't a property of obj or you don't know whether it is). My question isn't about how .call works in general. My question is about this case, where I can't see an obvious reason for using .call as opposed to the object-property syntax.

like image 309
ajb Avatar asked Aug 31 '13 17:08

ajb


1 Answers

There is no difference between the two.

If we check the language specification for normal function calls and then Function.prototype.call we can see that they behave exactly the same.

Namely,

x.f.call(x) does this:

Return the result of calling the [[Call]] internal method of func, providing thisArg as the this value and argList as the list of arguments.

Where a normal call does:

Return the result of calling the [[Call]] internal method on func, providing thisValue as the this value and providing the list argList as the argument values.

Where this has resolution (specified in 11.2.3 7.b.i in the spec).

All modern JavaScript implementations (yes, even IE8 modern) respect this.

like image 143
Benjamin Gruenbaum Avatar answered Oct 25 '22 12:10

Benjamin Gruenbaum