Subclassing Javascript Arrays. TypeError: Array.prototype.toString is not generic

后端 未结 7 1223
独厮守ぢ
独厮守ぢ 2020-11-28 06:30

Is it possible to subclass and inherit from javascript Arrays?

I\'d like to have my own custom Array object that has all the features of an Array, but contains addit

相关标签:
7条回答
  • 2020-11-28 07:19

    ES6 minimal runnable example with custom constructor

    If you also want to override the constructor, then some extra care is needed because some of the methods will need the old constructor.

    Using the techniques mentioned at: How can I extend the Array class and keep its implementations we can reach:

    #!/usr/bin/env node
    
    const assert = require('assert');
    
    class MyArray extends Array {
      constructor(nodes, myint) {
        super(...nodes);
        this.myint = myint;
      }
    
      static get [Symbol.species]() {
        return Object.assign(function (...items) {
          return new MyArray(new Array(...items))
        }, MyArray);
      }
    
      inc() { return this.myint + 1; }
    }
    
    const my_array = new MyArray([2, 3, 5], 9);
    assert(my_array[0] === 2);
    assert(my_array[1] === 3);
    assert(my_array[2] === 5);
    
    assert(my_array.myint === 9);
    
    assert(my_array.inc() === 10);
    
    assert(my_array.toString() === '2,3,5');
    
    my_slice = my_array.slice(1, 2);
    assert(my_slice[0] === 3);
    assert(my_slice.constructor === MyArray);
    
    

    Getting the index notation [] without Arrray has been asked at: Implement Array-like behavior in JavaScript without using Array

    Tested in Node.js v10.15.1.

    0 讨论(0)
提交回复
热议问题