var obj = {
name: 99,
age: 777
}
function Watch(obj, prop) {
var that = this;
that.val = obj[prop];
that.setFuns = [];
Object.defineProperty(obj, prop, {
get: function() {
console.log("get", prop, that.val)
return that.val
},
set: function(value) {
that.val = value;
console.log("set", prop, that.val)
that.setFuns.forEach(function(item) {
item(that.val);
});
return that.val;
}
})
}
Watch.prototype.addSetFuns = function(fn) {
this.setFuns.push(fn);
}
var watch = new Watch(obj, "name");
watch.addSetFuns(function(val) {
alert(val)
})
setTimeout(function() {
obj.name = 777
}, 3000)