// 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事件进行更改,但这不是我想要的,我想严格跟踪对象本身的变化以供任何使用,上面的代码是只是一个例子.
解决方法
那么你可以使用get和set方法使它成为一个实际的对象:
// 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/