Search code examples
javascriptprototypedefineproperty

Redefining .push() with Object.defineProperty that returns array


If I have a property on an object created by calling Object.defineProperty on the prototype of its constructor function that returns an array such as:

function Foo() { 
    this._bar = []; 
}

Object.defineProperty(Foo.prototype, 'bar', { 
    get: function () { 
        return this._bar; 
    }
});

How can I capture and override calls to .push() on the derived barproperty?


Solution

  • Here is a full, working example of how you can override push on your property.

    function Foo() { 
        this._bar = []; 
        var oldPush = this._bar.push;
        this._bar.push = function(){
    
            for(var i = 0; i < arguments.length; i++){
                //do something with each element if needed
                $('body').append("<p>INSERTING VALUE: " + arguments[i] + "</p>");
            }
    
            oldPush.apply(this, arguments);
        };
    }
    
    Object.defineProperty(Foo.prototype, 'bar', { 
        get: function () { 
            return this._bar; 
        }
    });
    

    Check this out for a demo: JSFiddle

    UPDATE: Edited the code to be able to call push with a list of params, e.g. foo.bar.push(1, 2, 3).