跟踪对象是否已更改

问题描述:

// A simple Javascript Object / String
var object = "hello";

// Imagine a button in the DOM, and if it's clicked the object value will change
document.getElementById("button").onclick = function(){
   window.object = "hello world";
}

// Now I would like to track and do something when the object is changed, ex:
object.onreadystatechange = function(){
   alert(object);
}

注意:这听起来很愚蠢,因为我可以得到改变在按钮上的 onclick 事件中,但这不是我想要的,我想严格跟踪对象本身的变化以供任何使用,上面的代码是只是一个例子。

Note: This could sound stupid, because I could get the change in the onclick event on the button, but this is not what I want, I want strictly to track the change on the object itself for any kind of use, the above code is is just an example.

你可以用get和set方法把它变成一个实际的对象:

Well you can make it an actual oject with get and set methods:

// A simple Javascript Object 
var object = new (function(){
    this.text = 'hello';

    this.setText = function(msg){
         this.text = msg
         //on change event
    }
})();

// Imagine a button in the DOM, and if it's clicked the object value will change
document.getElementById("button").onclick = function(){
   object.setText('New Text');
}

这是一个演示小提琴: http://jsfiddle.net/maniator/BSYpz/

Here is a demo fiddle: http://jsfiddle.net/maniator/BSYpz/