gpt4 book ai didi

javascript - Prototype 在这个 Array slice 调用中,为什么?

转载 作者:数据小太阳 更新时间:2023-10-29 04:04:48 25 4
gpt4 key购买 nike

我正在阅读 JS 函数的 arguments 变量的 MDN 页面:

https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments

我知道 arguments 不是数组,所以这行不通:

var a = arguments.slice();

MDN 上的解决方案是这样做:

var args = Array.prototype.slice.call(arguments);

为什么使用 Array.prototype 而不仅仅是 Array.slice.call(arguments)?在这里使用原型(prototype)重要吗?

最佳答案

Why use Array.prototype and not just Array.slice.call(arguments)?

Array.slice 方法是 Array and String Generics 的一部分,一组 “静态” 方法实现为 ArrayString 构造函数的属性。

这些方法非标准,它们仅在基于 Mozilla 的实现中可用。

我发现这些方法和标准方法之间存在很多混淆,但您应该知道它们是不一样的,如果您进行测试:

Array.slice === Array.prototype.slice; // false

你会发现它们是不同的方法。

顺便说一下,如果你在哪里使用那个方法,你不需要使用 call 方法,第一个参数是将用作 this< 的对象 值(Array.slice(arguments))。

Is using the prototype significant here?

是的,Array 构造器只是一个函数,标准的slice 方法,所有其他“数组方法”都定义在Array.prototype.

此对象 Array.prototype 是所有 Array 对象实例继承自的对象。

作为@Pointy说,您可以使用 Array 实例获取对该方法的引用:

 [].slice === Array.prototype.slice; // true

理论上,这会创建一个新的 Array 对象,并访问原型(prototype)链中的 slice 方法,但我记得有些实现开始优化这种属性访问,避免disposable 对象的创建,因此,在某些时候,它在性能方面也是完全一样的。

关于javascript - Prototype 在这个 Array slice 调用中,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6763555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com