How can I extend Array.prototype.push()?

Since push allows more than one element to be pushed, I use the arguments variable below to let the real push method have all arguments.

This solution only affects the arr variable:

arr.push = function () {
    //Do what you want here...
    return Array.prototype.push.apply(this, arguments);
}

This solution affects all arrays. I do not recommend that you do that.

Array.prototype.push = (function() {
    var original = Array.prototype.push;
    return function() {
        //Do what you want here.
        return original.apply(this, arguments);
    };
})();

Leave a Comment