Sagiv Ofek
Sagiv Ofek

Reputation: 25280

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?

Upvotes: 4

Views: 266

Answers (2)

Kijewski
Kijewski

Reputation: 26043

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

Upvotes: 2

Pointy
Pointy

Reputation: 413996

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

Upvotes: 6

Related Questions