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

后端 未结 7 1267
独厮守ぢ
独厮守ぢ 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:17

    I've created a simple NPM module that solves this - inherit-array. It basically does the following:

    function toArraySubClassFactory(ArraySubClass) {
      ArraySubClass.prototype = Object.assign(Object.create(Array.prototype),
                                              ArraySubClass.prototype);
    
      return function () {
        var arr = [ ];
        arr.__proto__ = ArraySubClass.prototype; 
    
        ArraySubClass.apply(arr, arguments);
    
        return arr;
      };
    };
    

    After writing your own SubArray class you can make it inherit Array as follows:

    var SubArrayFactory = toArraySubClassFactory(SubArray);
    
    var mySubArrayInstance = SubArrayFactory(/*whatever SubArray constructor takes*/)
    

提交回复
热议问题