侦听对Javascript对象值的更改

red*_*nce 10 javascript jquery

是否有可能(使用jQuery或其他方式)监听非DOM Javascript对象(或变量)的值的变化?所以,例如,我有:

function MyObject()
{
    this.myVar = 0;
}

var myObject = new MyObject();
myObject.myVar = 100;
Run Code Online (Sandbox Code Playgroud)

有没有办法在myVar更改值时调用并调用函数?我知道我可以使用getter/setter,但在以前版本的IE中不支持它们.

And*_*ris 11

基本上你有两个选择

  • 使用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*
Run Code Online (Sandbox Code Playgroud)

示例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*
Run Code Online (Sandbox Code Playgroud)


mpl*_*jan 4

如果IE很重要,我猜你对Watch不感兴趣

但有人似乎写了一个垫片,使这个问题重复

观察 JavaScript 中对象属性的变化