我希望擴展對象和數組類,以便在構造後能夠聽取對其實例所做的任何更改。如何偵聽動態添加的對象字段中的更改?
最好的我現在能做的就是添加自定義獲取和設置功能在初始化/建築實例的給定字段:
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;
}
提前感謝!
所以你想看任何*屬性? – 2012-04-13 17:33:27
是的,而不是偵聽預定義的字段集我寧願聽正在調用的函數來創建新字段,並設置它們的值,當我說myObj.randomfieldname = somevalue; – Marcus 2012-04-15 10:22:14
好吧,我想你已經知道了,但讓我只是說,地獄裏沒有辦法讓你獲得像這樣的工作,並有適當的瀏覽器支持。 – 2012-04-16 04:28:52