这个Array切片调用中的原型,为什么? [英] Prototype in this Array slice call, why?
问题描述
我正在阅读JS函数的参数变量的MDN页面:
I was reading the MDN page for the JS Function's arguments variable:
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments
我知道参数不是数组,所以这不起作用:
I understand that arguments is not an Array so this won't work:
var a = arguments.slice();
MDN上的解决方案是这样做的:
The solution on MDN is do do this:
var args = Array.prototype.slice.call(arguments);
为什么要使用 Array.prototype
而不仅仅是 Array.slice.call(参数)
?在这里使用原型有意义吗?
Why use Array.prototype
and not just Array.slice.call(arguments)
? Is using the prototype significant here?
推荐答案
为什么要使用Array.prototype而不仅仅是Array.slice .call(arguments)?
Why use Array.prototype and not just Array.slice.call(arguments)?
Array.slice
方法属于 数组和字符串泛型 ,一套static方法实现为 Array
和 String
构造函数的属性。
The Array.slice
method is part of the Array and String Generics, a set of "static" methods implemented as properties of the Array
and String
constructors.
这些方法非标准,它们仅在基于Mozilla的实现中可用。
Those methods are non-standard, they are available just in Mozilla-based implementations.
我看到这些方法和标准方法之间存在很多混淆,但如果你测试的话,你应该知道它们不一样:
I've seen a lot confusion between those methods and the standard ones, but you should know that they aren't the same, if you test:
Array.slice === Array.prototype.slice; // false
你会发现它们是不同的方法。
You will find that they are different methods.
顺便说一句,如果你在那里使用那个方法,你不需要使用调用
方法,第一个参数就是用作此
值( Array.slice(arguments)
)。
And by the way, if you where using that method, you don't need to use the call
method, the first argument is the object that will be used as the this
value (Array.slice(arguments)
).
这里使用的原型是否显着?
Is using the prototype significant here?
是的, Array
构造函数只是一个函数,标准 slice
方法,所有其他数组方法都在 Array.prototype
。
Yes, the Array
constructor is just a function, the standard slice
method, and all the other "array methods" are defined on Array.prototype
.
此对象 Array.prototype
是一个所有Array对象实例都继承自。
This object, Array.prototype
, is the one in which all Array object instances inherit from.
as @ Pointy 说,您可以使用Array实例获取对该方法的引用:
As @Pointy says, you could get a reference to the method using an Array instance:
[].slice === Array.prototype.slice; // true
理论上,这将创建一个新的Array对象,并访问 slice
原型链中的方法,但我记得有些实现开始优化这种属性访问,避免创建一次性对象,所以在某种程度上,就性能而言,它也将完全相同。
This, in theory, will create a new Array object, and access the slice
method up in the prototype chain, but I remember that some implementations are starting to optimize this kind of property access, avoiding the creation of the disposable object, so, at some point, it will be exactly the same also talking in terms of performance.
这篇关于这个Array切片调用中的原型,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!