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

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);    };})();


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);};


Array.prototype.push was introduced in JavaScript 1.2. It is really as simple as this:

Array.prototype.push = function() {    for( var i = 0, l = arguments.length; i < l; i++ ) this[this.length] = arguments[i];    return this.length;};

You could always add something in the front of that.