javascript - 在 JavaScript 中扩展基类 Array

标签 javascript extend

我有一个扩展基本数组类的自定义数组类。我有一个易于使用的自定义方法

export class ExampleArray extends Array {
    includesThing(thing) {
        ...

        return false
    }
}

但是现有的filtermap等方法返回一个数组实例。我想使用这些方法返回 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.mapsuper.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 方法,包括 spliceslice 和(实验性的)flat平面 map 。如果您希望它们返回自定义类实例化而不是默认的 Array 实例,请遵循相同的模式:隐藏 Array.prototype 函数名称,并返回一个 新的 ExampleArray 填充了 applyArray.prototype 方法的结果:

<fnName>(...args) {
  return new ExampleArray(
    ...super.<fnName>.apply(this, args)
  );
}

关于javascript - 在 JavaScript 中扩展基类 Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52529092/

相关文章:

javascript - 使用 CSS transform 属性使元素响应

javascript - 缩小网页以适应 iframe 尺寸

google-maps - Google Map V3 - 使用绘图管理器绘图时撤消最后一点

class - 如何强制模式编译的类将特定的类扩展到模式之外

javascript - 对象中的回调函数默认值应该是什么?

javascript - 嵌套对象扩展并跳过未定义的属性(在 Angular 或 Underscore 中)

javascript - 如何在新窗口中从 slider 打开图像

javascript - 如何让 jquery 找到该行并在成功时触发一个 Action (使用 "this")

javascript - 回调函数抛出错误

css - 将@extend 与父样式合并并创建一个类名