我有一个扩展基本数组类的自定义数组类。我有一个易于使用的自定义方法
export class ExampleArray extends Array {
includesThing(thing) {
...
return false
}
}
但是现有的filter
、map
等方法返回一个数组实例。我想使用这些方法返回 ExampleArray
的实例。
我可以找到这些方法的接口(interface),但找不到它们的实现。如何调用父方法并返回我的自定义 EampleArray?类似下面的内容
export class ExampleArray extends Array {
filter() {
result = Array.filter()
array = new ExampleArray()
array.push(...result)
return array
}
或者这是扩展数组以创建自定义数组的正确方法吗?
最佳答案
您需要隐藏现有的 .filter
和 .map
以便在调用 ExampleArray< 的实例时
,将调用您的新 函数,而不是Array.prototype
函数。在 ExampleArray
中,您可以访问 super.map
和 super.filter
以获取 Array.prototype
方法。例如:
class ExampleArray extends Array {
constructor(...args) {
super(...args);
}
hasMoreThanTwoItems() {
// example custom method
return this.length > 2;
}
isExampleArray() {
return true;
}
// Shadow Array.prototype methods:
filter(...args) {
return new ExampleArray(
// Spread the result of the native .filter into a new ExampleArray instance:
...super.filter.apply(this, args)
);
}
map(...args) {
return new ExampleArray(
...super.map.apply(this, args)
);
}
}
const exampleArray = new ExampleArray(3, 4, 5, 6, 7);
// true, filtering will result in 3 items
console.log(
exampleArray
.filter(e => e > 4)
.hasMoreThanTwoItems()
);
// false, filtering will result in zero items
console.log(
exampleArray
.filter(e => e > 10)
.hasMoreThanTwoItems()
);
// true, is an ExampleArray
console.log(
exampleArray
.map(e => e * 2)
.isExampleArray()
);
请注意,还有其他返回数组的 Array 方法,包括 splice
、slice
和(实验性的)flat
和 平面 map
。如果您希望它们返回自定义类实例化而不是默认的 Array
实例,请遵循相同的模式:隐藏 Array.prototype
函数名称,并返回一个 新的 ExampleArray
填充了 apply
Array.prototype
方法的结果:
<fnName>(...args) {
return new ExampleArray(
...super.<fnName>.apply(this, args)
);
}
关于javascript - 在 JavaScript 中扩展基类 Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52529092/