javascript – 跟踪对象是否已更改

前端之家收集整理的这篇文章主要介绍了javascript – 跟踪对象是否已更改前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
// 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/

原文链接:https://www.f2er.com/js/156339.html

猜你在找的JavaScript相关文章