Extending built-in classes

// 內建方法返回新的 array (filter、map),他們是靠 constructor 屬性
// add one more method to it (can do more)
class PowerArray extends Array {
  isEmpty() {
    return this.length === 0;
  }
}

let arr = new PowerArray(1, 2, 5, 10, 50);
alert(arr.isEmpty()); // false

let filteredArr = arr.filter(item => item >= 10);
alert(filteredArr); // 10, 50
alert(filteredArr.isEmpty()); // false

// 從上面的例子當 arr.filter(),新的 array 是用 new PowerArray,我們可以用 PowerArray 的屬性
arr.constructor === PowerArray

// 加上特殊靜態 getter Symbol.species,返回使用 filter、map 的 constructor。
class PowerArray extends Array {
  isEmpty() {
    return this.length === 0;
  }

  // built-in methods will use this as the constructor
  static get [Symbol.species]() {
    return Array;
  }
}

let arr = new PowerArray(1, 2, 5, 10, 50);
alert(arr.isEmpty()); // false

// filter creates new array using arr.constructor[Symbol.species] as constructor
let filteredArr = arr.filter(item => item >= 10);

// filteredArr is not PowerArray, but Array
alert(filteredArr.isEmpty()); // Error: filteredArr.isEmpty is not a function

No static inheritance in built-ins

內建物件有自己靜態屬性, 像是Object.keys, Array.isArray 等等,原生 classes 會互相繼承,像是 Array extends Object,一般來說靜態、非靜態屬性都會互相繼承,但原生的 class 不會互相繼承靜態屬性,若 Rabbit extends Animal

  1. Rabbit.methods are callable for Animal.methods, because Rabbit.[[Prototype]] = Animal.

  2. new Rabbit().methods are also available, because Rabbit.prototype.[[Prototype]] = Animal.prototype.

Last updated