user1569339
user1569339

Reputation: 683

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?

Upvotes: 1

Views: 2110

Answers (1)

p e p
p e p

Reputation: 6674

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).

Upvotes: 4

Related Questions