Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript foo.call(object) vs. object.foo()

i was looking on the jQuery source code and then i saw that they use foo.call(context) instead of context.foo().
for example- assuming this is array they use:

return slice.call( this );

instead of:

return this.slice();

what is the difference and is it the prefer way (in terms of performance) doing those calls?

like image 236
Sagiv Ofek Avatar asked Feb 21 '23 07:02

Sagiv Ofek


2 Answers

The problem is that "foo" might not actually be a property of "context". When that's the case, the only real choice is to use .call() (or .apply(), as appropriate).

If you do have an object with a "foo" property that's a function, then there's no real reason to use .call().

like image 198
Pointy Avatar answered Feb 28 '23 02:02

Pointy


In addition to @Pointy's answer, the direct call of a member function seems to be much faster than Class.prototype.foo:

http://jsperf.com/javascript-foo-call-object-vs-object-foo

like image 45
kay Avatar answered Feb 28 '23 02:02

kay