[英]What is the difference between these two ways to leverage the arguments object in a JavaScript function?
In the documentation for the Array.prototype.slice
method it says: 在
Array.prototype.slice
方法的文档中说:
Binding can be done with the .call function of Function.prototype and it can also be reduced using [].slice.call(arguments) instead of Array.prototype.slice.call.
可以使用Function.prototype的.call函数完成绑定,也可以使用[] .slice.call(arguments)而不是Array.prototype.slice.call减少绑定。
function getArgs() {
var args = [].slice.call(arguments);
return args;
}
getArgs(1,2,3); // returns [1, 2, 3]
function getArgs2() {
var args = Array.prototype.slice.call(arguments);
return args;
}
getArgs2(1,2,3); // returns [1, 2, 3]
Essentially what is the difference? 本质上有什么区别? Is there a performance benefit using one over the other method?
使用一种方法是否比使用另一种方法具有性能优势? Or is the former just easier to type out?
还是前者更容易输入?
Those both do the same thing, which is to call the array .slice()
method. 两者都做同样的事情,那就是调用数组
.slice()
方法。 The first way gets at the function via the implicit prototype lookup from a new empty array, and the other goes explicitly to the Array.prototype
object. 第一种方法是通过从一个新的空数组进行隐式原型查找来获取函数,另一种方法显式地转到
Array.prototype
对象。 There is probably a performance difference but it's not significant or relevant, since both ways throw away a lot of performance anyway: passing the arguments
object out of a function is likely to make the runtime system give up on optimizing the function. 性能可能存在差异,但并不重要或无关紧要,因为两种方式都将浪费很多性能:将
arguments
对象从函数中传递出去可能会使运行时系统放弃优化功能。
To avoid that performance penalty, a simple local for
loop should be used instead: 为避免性能下降,应改为使用简单的本地
for
循环:
function foo() {
var args = [];
for (var i = 0; i < arguments.length; ++i) args[i] = arguments[i];
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.