How to extend Array.prototype.push()?

后端 未结 6 725
遥遥无期
遥遥无期 2020-11-27 02:45

I\'m trying to extend the Array.push method so that using push will trigger a callback method, then perform the normal array function.

I\'m not quite sure how to do

6条回答
  •  忘掉有多难
    2020-11-27 03:29

    First you need subclass Array:

    ES6 (https://kangax.github.io/compat-table/es6/):

    class SortedArray extends Array {
        constructor(...args) {
            super(...args);
        }
        push() {
            return super.push(arguments);
        }
    }
    

    es5:(proto is almost deprecated but it is the only solution for now)

    function SortedArray() {
        var arr = [];
        arr.push.apply(arr, arguments);
        arr.__proto__ = SortedArray.prototype;
        return arr;
    }
    SortedArray.prototype = Object.create(Array.prototype);
    
    SortedArray.prototype.push = function() {
        this.arr.push(arguments);
    };
    

提交回复
热议问题