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

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

    I've tried to do this sort of thing before; generally, it just doesn't happen. You can probably fake it, though, by applying Array.prototype methods internally. This CustomArray class, though only tested in Chrome, implements both the standard push and custom method last. (Somehow this methodology never actually occurred to me at the time xD)

    function CustomArray() {
        this.push = function () {
            Array.prototype.push.apply(this, arguments);
        }
        this.last = function () {
            return this[this.length - 1];
        }
        this.push.apply(this, arguments); // implement "new CustomArray(1,2,3)"
    }
    a = new CustomArray(1,2,3);
    alert(a.last()); // 3
    a.push(4);
    alert(a.last()); // 4
    

    Any Array method you intended to pull into your custom implementation would have to be implemented manually, though you could probably just be clever and use loops, since what happens inside our custom push is pretty generic.

提交回复
热议问题