在ES6 / ES2015中容易实例化子类数组

Easy instantiation of sub-classed array in ES6 / ES2015

本文关键字:实例化 子类 数组 ES6 ES2015      更新时间:2023-09-26

我看到过类似的子类化数组的例子:

class Scores extends Array {
  constructor(len) {
    super(len);
  }
}
var s = new Scores();  // alloc
s[0] = 1; // assign

是否有可能在继承子类的同时保留通常的赋值样式,即:

var s = new Scores([1,2,3]); // alloc + assign

另外,如何在子类中引用给定的值?例如,创建值的平均值?

  avg() {
    var sum = this.???.reduce((x, y) => x + y, 0);
    return sum / this.???.length;
  }

是否有可能在继承子类的同时保留通常的赋值样式

当然,构造函数可以做任何你想让它做的事情。如

constructor(values) {
  super();
  this.push(...values);
}

另外,如何在子类中引用给定的值?

由于this子类数组,您可以直接执行

avg() {
  var sum = this.reduce((x, y) => x + y);
  return sum / this.length;
}

注意,原生对象的子类化还不是很受支持。