[英]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()
. 我正在查看jQuery源代码 ,然后我看到他们使用
foo.call(context)
而不是context.foo()
。
for example- assuming this
is array they use: 例如 - 假设
this
是他们使用的数组:
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? 有什么区别,是否是这些电话的首选方式(在性能方面)?
The problem is that "foo" might not actually be a property of "context". 问题是“foo”实际上可能不是“上下文”的属性。 When that's the case, the only real choice is to use
.call()
(or .apply()
, as appropriate). 如果是这样的话,唯一真正的选择是使用
.call()
或.apply()
如适用)。
If you do have an object with a "foo" property that's a function, then there's no real reason to use .call()
. 如果你有一个具有“foo”属性的对象是一个函数,那么没有真正的理由使用
.call()
。
In addition to @Pointy's answer, the direct call of a member function seems to be much faster than Class.prototype.foo: 除了@Pointy的答案之外,成员函数的直接调用似乎比Class.prototype.foo快得多:
http://jsperf.com/javascript-foo-call-object-vs-object-foo http://jsperf.com/javascript-foo-call-object-vs-object-foo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.