我有这个复制数组例程:
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
不会复制原始原型(prototype)?
所以也许我应该这样做:
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;
};
最佳答案
不,没必要,slice()
就足够了,因为它会调用传入对象的构造函数。 (如果对象是一个数组,它将调用 Array
构造函数 - 否则,它将调用对象具有的任何构造函数。)参见 specification :
- Let A be ArraySpeciesCreate(O, count).
(...assign to properties of A and return A)
其中 ArraySpeciesCreate is :
a. Let C be Get(originalArray, "constructor").
9.Return Construct(C, «length»).
换句话说 - 如果您在一个类数组对象上调用 Array.prototype.slice
,其原型(prototype)从 Array 扩展但不是 Array.prototype
,传递的将调用对象的构造函数。无需手动设置原型(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();
关于javascript - 调用 Array.prototype.slice 时,新数组是否具有相同的原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57033675/