javascript – 跟踪对象是否已更改

前端之家收集整理的这篇文章主要介绍了javascript – 跟踪对象是否已更改前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. // A simple Javascript Object / String
  2. var object = "hello";
  3.  
  4. // Imagine a button in the DOM,and if it's clicked the object value will change
  5. document.getElementById("button").onclick = function(){
  6. window.object = "hello world";
  7. }
  8.  
  9. // Now I would like to track and do something when the object is changed,ex:
  10. object.onreadystatechange = function(){
  11. alert(object);
  12. }

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

解决方法

那么你可以使用get和set方法使它成为一个实际的对象:
  1. // A simple Javascript Object
  2. var object = new (function(){
  3. this.text = 'hello';
  4.  
  5. this.setText = function(msg){
  6. this.text = msg
  7. //on change event
  8. }
  9. })();
  10.  
  11. // Imagine a button in the DOM,and if it's clicked the object value will change
  12. document.getElementById("button").onclick = function(){
  13. object.setText('New Text');
  14. }

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

猜你在找的JavaScript相关文章