我希望扩展 Object 和 Array 类,这样我就能够在构造后监听对它们的实例所做的任何更改。
我现在能做的最好的事情是为在初始化/构造实例时给定的字段添加自定义 get 和 set 函数:
var myObj = new CustomObject({name:'foo'});
myObj.name = 'bar'; // this will log "'name' in 'myObj' updated:'bar'"
//however:
myObj.age = 85; // this mutation will slip by unnoticed,
// since the 'age' field was never specified
// at initialization meaning no custom set / get
// functions where attached.
有没有办法实现以下功能?
var myObj = new CustomObject();
myObj.name = 'foo';// this should log something like:
// "A new field 'name' was created for myObj with value 'foo'"
注意:我正在寻找不涉及轮询的解决方案。
我现在拥有的(导致第一个代码块中显示的功能):
function CustomObject(data) {
var that = this;
for(var field in data){
prepField(field);
}
function prepField(field){
Object.defineProperty( that, field, {
set: function(val){
data[field] = val;
console.log(field,'in',that,'updated:',val);
},
get: function(){
console.log(field,'in',that,'requested');
return data[field];
},
enumerable:true
});
}
return this;
}
提前致谢!