函数式编程和 ES6 数组子类化



我在Javascript ES6中子类化了一个数组,如下所示:

export class MyList extends Array {
  constructor(...args) {
      super(...args);
  }
}

但是,一旦我使用像mapfilter这样的函数式方法,它们就会再次返回一个正常的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

最新更新