我在Javascript ES6中子类化了一个数组,如下所示:
export class MyList extends Array {
constructor(...args) {
super(...args);
}
}
但是,一旦我使用像map
或filter
这样的函数式方法,它们就会再次返回一个正常的Javascript数组。
let myList = new MyList();
myList[0] = {id: 'a', name: 'Tom'};
myList[1] = {id: 'b', name: 'Alice'};
let mapedList = myList.map((elem) => elem.name);
console.log(myList instanceof MyList); // true
console.log(myList instanceof Array); // true
console.log(mapedList instanceof MyList); // false
console.log(mapedList instanceof Array); // true
那么我怎样才能正确地子类化一个Javascript数组而不会遇到所有这些问题呢?
你可以实现一个名为 from
的小static
函数,它可以使用 ECMAScript 2015 的Reflection API
将结果Array
转换为MyList
。
您的class
将如下所示:
export class MyList extends Array {
constructor(...args) {
super(...args);
}
static from(arr) {
Reflect.setPrototypeOf(arr, new MyList);
return arr;
}
}
然后,在您的代码中,您只需将map
调用包装from
函数调用中,如下所示:
let mapedList = MyList.from(myList.map((elem) => elem.name));
您还可以像Array.from
一样修改它以支持更多类型的objects
。