是否有可能(使用 jQuery 或其他方式)监听非 DOM Javascript 对象(或变量)值的变化?因此,例如,我有:
function MyObject()
{
this.myVar = 0;
}
var myObject = new MyObject();
myObject.myVar = 100;
有没有办法监听 myVar
的值何时发生变化并调用函数?我知道我可以使用 getter/setter,但它们在以前版本的 IE 中不受支持。
最佳答案
基本上你有两个选择
- 使用仅在 Firefox 中可用的非标准
watch
方法 - 使用旧版 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 - 监听 Javascript 对象值的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6689931/