基本上你有两个选择
- 使用非标准
watch
方法仅在Firefox可以未在旧的IE版本支持
- 使用getter和setter
第三和跨平台的选择是使用轮询,这没有那么大
实施例的watch
var myObject = new MyObject();
// Works only in Firefox
// Define *watch* for the property
myObject.watch("myVar", function(id, oldval, newval){
alert("New value: "+newval);
});
myObject.myVar = 100; // should call the alert from *watch*
的getters
实施例和setters
function MyObject(){
// use cache variable for the actual value
this._myVar = undefined;
}
// define setter and getter methods for the property name
Object.defineProperty(MyObject.prototype, "myVar",{
set: function(val){
// save the value to the cache variable
this._myVar = val;
// run_listener_function_here()
alert("New value: " + val);
},
get: function(){
// return value from the cache variable
return this._myVar;
}
});
var m = new MyObject();
m.myVar = 123; // should call the alert from *setter*
可能重复的[JavaScript的 - 手表给对象特性的变化(http://stackoverflow.com/questions/1269633/javascript-watch-for-object-properties - 改变) – mplungjan