简体   繁体   English

javascript foo.call(object)与object.foo()

[英]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.

相关问题 Javascript object 行为不同,基于索引结尾: foo 与 foo() - Javascript object to behave differently, based on index ending: foo vs. foo() JavaScript:`Object.prototype.toString.call(foo)` 和 `Object.prototype.toString(foo)` 之间的差异 - JavaScript: differences between `Object.prototype.toString.call(foo)` and `Object.prototype.toString(foo)` JavaScript:$('foo')vs document.getElementById('foo') - JavaScript: $('foo') vs document.getElementById('foo') 为什么我们必须在foo.call(this,param1,param2)中传递“ this”参数? - Why do we have to pass “this” parameter in foo.call(this, param1, param2)? typeof foo ['bar']!=='undefined'与foo中的'bar' - typeof foo['bar'] !== 'undefined' vs. 'bar' in foo 静态foo =“ bar”与MyClass.foo =“ bar” - static foo = “bar” vs. MyClass.foo = “bar” 为什么 foo object 没有改变? - Why is foo object not changing? $(“'” + foo +“'”)与$(foo) - $(“'” + foo + “'”) vs $(foo) 如果foo在JavaScript文件中定义并包含在html中,那么哪个对象而不是window拥有(全局)函数foo作为属性? - What object, instead of window, has (global) function foo as a property if foo is defined in a javascript file and included from html? “var FOO = FOO || {}”(为该变量分配一个变量或一个空对象)在 Javascript 中是什么意思? - What does "var FOO = FOO || {}" (assign a variable or an empty object to that variable) mean in Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM