// 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);
}
Run Code Online (Sandbox Code Playgroud)
注意:这听起来很愚蠢,因为我可以onclick在按钮上获得事件的变化,但这不是我想要的,我想严格跟踪对象本身的变化以供任何使用,上面的代码是只是一个例子.
Javascript不允许您在任意对象/变量上设置程序化观察点/事件.
您可以使用封装来隐藏对象内部的各个值,只允许通过具有您想要的副作用的专用"setter"函数来修改它们.
那么你可以使用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');
}
Run Code Online (Sandbox Code Playgroud)
这是一个演示小提琴:http://jsfiddle.net/maniator/BSYpz/