我有一個這樣的對象: var obj = {key1: "hello", key2: {keyA: "1", keyB: "2"}}
如何觀看對象的值,它是對象
我目前使用此代碼來觀看時的選擇的關鍵變化的值:
if (!Object.prototype.watch) {
Object.defineProperty(Object.prototype, "watch", {
enumerable : false,
configurable : true,
writable : false,
value : function(prop, handler) {
var oldval = this[prop], newval = oldval, getter = function() {
return newval;
}, setter = function(val) {
oldval = newval;
return newval = handler.call(this, prop, oldval, val);
};
if (
delete this[prop]) {// can't watch constants
Object.defineProperty(this, prop, {
get : getter,
set : setter,
enumerable : true,
configurable : true
});
}
}
});
}
// object.unwatch
if (!Object.prototype.unwatch) {
Object.defineProperty(Object.prototype, "unwatch", {
enumerable : false,
configurable : true,
writable : false,
value : function(prop) {
var val = this[prop];
delete this[prop];
// remove accessors
this[prop] = val;
}
});
}
obj.watch("key1", function(id, oldval, newval) {
console.log(newval)
});
`
和當「你好」變化時,我可以處理事件。但是,當一個對象的屬性改變(Key2)而沒有用前一個函數對象的所有元素(KeyA和KeyB)時,我怎麼能處理一個事件?
更好說..當一個對象發生變化時可能得到通知而不監視該對象的所有元素?
Thaaanku