Geuis Geuis - 1 year ago 136
Javascript Question

How to extend Array.prototype.push()?

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 this, but here's some code I've been playing with unsuccessfully.

arr = [];
arr.push = function(data){

//callback method goes here

this = Array.push(data);
return this.length;



Answer Source

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.

    var original = Array.prototype.push;
    return function() {
        //Do what you want here.
        return original.apply(this,arguments);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download