Symbol.species Keeps Subclasses Predictable

Subclasses of Array control what slice and map return through Symbol.species: default keeps the subclass, override restores plain Array.

JavascriptData Integrity

Code

javascriptsnippet
23 lines
class SortedList extends Array {
  get sorted() {
    return [...this].sort((a, b) => a - b);
  }
}

const list = new SortedList(3, 1, 2);

// species 未覆盖:slice/map 等派生方法默认返回子类实例
console.log('sorted view:', list.sorted);
console.log('slice is SortedList:', list.slice(0, 2) instanceof SortedList);

// 覆盖 species 为 Array:派生方法改回基类,不带子类语义
class PlainSlices extends Array {
  static get [Symbol.species]() {
    return Array;
  }
}

const tail = new PlainSlices(1, 2, 3, 4);
const slice = tail.slice(2);
console.log('slice is Array:', slice instanceof Array);
console.log('slice is PlainSlices:', slice instanceof PlainSlices);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

sorted view: [ 1, 2, 3 ]
slice is SortedList: true
slice is Array: true
slice is PlainSlices: false

How it works

Symbol.species Keeps Subclasses Predictable is built around the classes SortedList and PlainSlices.

Demo state sits in top-level bindings: list, tail, slice.

It builds and returns a fresh value rather than reusing its inputs.

Caveats

  • There are no external packages; every API used ships with the language.

Putting it to use

Labels in the output track the sequence: sorted view:, slice is SortedList:, slice is Array:.

Core lines

return [...this].sort((a, b) => a - b);

Interactive Tools for This Topic

FAQ

Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. Its state lives in module-level bindings: `list`, `tail`, `slice`.