调用Array.prototype.slice时,新数组是否具有相同的原型?

时间:2019-07-15 05:30:04

标签: javascript node.js

我有这个复制数组例程:

const copyArray = (a: HasIndex) => {

  const ret = a.slice(0);

  for (const [k, v] of Object.entries(a)) {
    ret[k] = v;
  }

  return ret;

};

我假设调用Array.prototype.slice不会复制原始原型吗?

所以也许我应该这样做:

const copyArray = (a: HasIndex) => {

  const ret = a.slice(0);

  for (const [k, v] of Object.entries(a)) {
    ret[k] = v;
  }

  Object.setPrototypeOf(ret, Object.getPrototypeOf(a)); // here?

  return ret;

};

1 个答案:

答案 0 :(得分:4)

否,没有必要,仅slice()就足够了,因为它将调用传递的对象的构造函数。 (如果对象是数组,则将调用Array构造函数-否则,它将调用对象具有的任何构造函数。)请参见specification

  
      
  1. 让我们成为ArraySpeciesCreate(O,count)。
  2.   
     

(...分配A的属性并返回A)

其中ArraySpeciesCreate is

  

a。令C为Get(originalArray,“ constructor”)。

     

9。返回Construct(C,«length»)。

换句话说-如果对原型从Array扩展但不是Array.prototype.slice的类数组对象调用Array.prototype,则将调用传递的对象的构造函数。无需手动设置原型:

class ExtendedArray extends Array {
  customMethod() {
    console.log('custom method');
  }
}
const e = new ExtendedArray();
const sliced = e.slice();
console.log(Object.getPrototypeOf(sliced) === ExtendedArray.prototype);
sliced.customMethod();