Object.defineProperty
如果我在通过调用返回数组的构造函数原型创建的对象上有一个属性,例如:
function Foo() {
this._bar = [];
}
Object.defineProperty(Foo.prototype, 'bar', {
get: function () {
return this._bar;
}
});
如何捕获和覆盖.push()
对派生bar
属性的调用?
Object.defineProperty
如果我在通过调用返回数组的构造函数原型创建的对象上有一个属性,例如:
function Foo() {
this._bar = [];
}
Object.defineProperty(Foo.prototype, 'bar', {
get: function () {
return this._bar;
}
});
如何捕获和覆盖.push()
对派生bar
属性的调用?
这是一个完整的工作示例,说明如何覆盖push
您的属性。
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;
}
});
看看这个演示:JSFiddle
更新:编辑代码以便能够使用参数列表调用 push,例如foo.bar.push(1, 2, 3)
.