千巷猫影
没有。但是,如果它真的那么重要,那么您有两个选项(第一个是测试的,第二个不是):首先,使用setter和getter,如下所示:var myobj = {a : 1};function create_gets_sets(obj) { // make this a framework/global function
var proxy = {}
for ( var i in obj ) {
if (obj.hasOwnProperty(i)) {
var k = i;
proxy["set_"+i] = function (val) { this[k] = val; };
proxy["get_"+i] = function () { return this[k]; };
}
}
for (var i in proxy) {
if (proxy.hasOwnProperty(i)) {
obj[i] = proxy[i];
}
}}create_gets_sets(myobj);然后你就可以做这样的事情:function listen_to(obj, prop, handler) {
var current_setter = obj["set_" + prop];
var old_val = obj["get_" + prop]();
obj["set_" + prop] = function(val) { current_setter.apply(obj, [old_val, val]); handler(val));}然后将侦听器设置为:listen_to(myobj, "a", function(oldval, newval) {
alert("old : " + oldval + " new : " + newval);}第二,我实际上忘了,我会在考虑这件事的时候提交:)编辑:哦,我记得:)你可以把手表的价值:上面给出了“a”,上面写着:function watch(obj, prop, handler) { // make this a framework/global function
var currval = obj[prop];
function callback() {
if (obj[prop] != currval) {
var temp = currval;
currval = obj[prop];
handler(temp, currval);
}
}
return callback;}var myhandler = function (oldval, newval) {
//do something};var intervalH = setInterval(watch(myobj, "a", myhandler), 100);myobj.set_a(2);