Javascript foo.call (object) vs. object.foo ()

I looked at the jQuery source code and then saw that instead of context.foo() they use foo.call(context) .
for example, if this is the array they use:

 return slice.call( this ); 

instead:

 return this.slice(); 

what's the difference, and does he prefer (in terms of performance) to make these calls?

+4
source share
2 answers

The problem is that β€œfoo” cannot actually be a β€œcontext”. In this case, the only real choice is to use .call() (or .apply() , if necessary).

If you have an object with the property β€œfoo”, that function, then there is no real reason to use .call() .

+6
source

In addition to @Pointy's answer, directly calling a member function seems a lot faster than Class.prototype.foo:

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

+2
source

Source: https://habr.com/ru/post/1415641/


All Articles