gpt4 book ai didi

javascript - 监听 Javascript 对象值的变化

转载 作者:可可西里 更新时间:2023-11-01 02:35:58 25 4
gpt4 key购买 nike

是否有可能(使用 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*

getterssetters 的示例

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com