首页 > 编程语言 >[Javascript] Using defineProperty to observe the object props changes

[Javascript] Using defineProperty to observe the object props changes

时间:2024-10-09 15:15:25浏览次数:8  
标签:object obj val read Javascript observe Getter Setter

const obj = {
  a: 1,
  b: 2,
  c: {
    a: 1,
    b: 2,
  },
};

function isObject(val) {
  return val !== null && typeof val === "object";
}

function observe(obj) {
  for (let key in obj) {
    let v = obj[key];
    if (isObject(v)) {
      observe(v);
    }
    Object.defineProperty(obj, key, {
      get() {
        console.log(key, "read", v);
        return v;
      },
      set(val) {
        if (val !== v) {
          console.log(key, "set", val);
          v = val;
        }
      },
    });
  }
}

observe(obj);

obj.a;
obj.a = 3;
obj.c.a;
obj.c.b = 3;

console.log(JSON.stringify(obj));

/*
a read 1
a set 3
c read { d: [Getter/Setter], e: [Getter/Setter] }
d read 1
c read { d: [Getter/Setter], e: [Getter/Setter] }
e set 3
a read 3
b read 2
c read { d: [Getter/Setter], e: [Getter/Setter] }
d read 1
e read 3
{"a":3,"b":2,"c":{"d":1,"e":3}}
*/

 

Using defineProperty can only observe the existing props, if we add a new prop, then we are not able to observe it anymore

observe(obj);

obj.f = 123; // not albe to observe the changes, due to observe function has been called with existing properties

 

Also we are not able to observe deleted prop:

observe(obj);

delete obj.b;

 

So defineProperty is limited only to existing props of the object. 

If we want to achieve better result, we have to use Proxy

标签:object,obj,val,read,Javascript,observe,Getter,Setter
From: https://www.cnblogs.com/Answer1215/p/18454212

相关文章

  • 【javascript 编程】Web前端之JavaScript动态添加类名的两种方法、区别、className、c
    通过className来添加或删除类名添加类名获取元素el.className="类名1类名2...";多个类名用空格隔开。移除类名获取元素名el.className="";直接等于一个空字符串即可删除类名。通过classList来添加或删除类名添加一个类名获取元素名el.classList.add("类名");。......
  • [Javascript] Using Proxy to observe the object
    constobj={a:1,b:2,c:{d:1,e:2,},};functionisObject(val){returnval!==null&&typeofval==="object";}functionobserve(obj){constproxy=newProxy(obj,{get(target,key){constv......
  • 解决ERROR ResizeObserver loop completed with undelivered notifications.
    https://www.cnblogs.com/luo9tian/p/18116299该报错虽然不影响项目运行,但是影响开发效率,总是弹出报错的黑框很烦人该报错原因:newResizeObserver包裹的方法,在布局发生变化时,不支持每帧都调用解决方法:用window.requestAnimationFrame包裹回调函数在App.vue/main.js中加......
  • 从混乱到整洁:JavaScript学习中的代码演变之旅
    学习中的代码演变在JavaScript的学习之旅中,初学者常产出略显混乱的代码,这实属正常。每个错误与不易理解的代码段都是成长的一部分,随着时间推移,你将逐渐掌握编写整洁代码的技巧。混乱中的创新追求完美并非初学者的首要任务,这样反而能激发你尝试多样化的解决方案。比如,在构建待办......
  • javascript学习——CSS 操作总结
    CSS操作CSS与JavaScript是两个有着明确分工的领域,前者负责页面的视觉效果,后者负责与用户的行为互动。但是,它们毕竟同属网页开发的前端,因此不可避免有着交叉和互相配合。本章介绍如何通过JavaScript操作CSS。HTML元素的style属性操作CSS样式最简单的方法,就是......
  • javascript学习——DOM 概述
    DOM概述DOMDOM是JavaScript操作网页的接口,全称为“文档对象模型”(DocumentObjectModel)。它的作用是将网页转为一个JavaScript对象,从而可以用脚本进行各种操作(比如增删内容)。浏览器会根据DOM模型,将结构化文档(比如HTML和XML)解析成一系列的节点,再由这些节点组......
  • JavaScript数组合并方法(concat()函数)
    在JavaScript中,concat方法用于连接两个或多个数组,并返回一个新数组。这不会改变现有的数组,而是返回一个包含了连接元素的新数组。解法1:基本的concat使用方法letarray1=[1,2,3];letarray2=[4,5];letarray3=array1.concat(array2);console.log(array3);//输......
  • 表单验证:FormValidation JavaScript 1.7
    FormValidation表单验证:JavaScript的最佳验证库::用ES6编写使用TypeScript进行类型安全零依赖没有jQuery可用作AMD、ES6模块和全局脚本灵活的:自定义图标自定义错误消息动态字段自定义有效和无效颜色动态启用、禁用验证器自定义错误信息位置Playnicewithformlibra......
  • [Javascript] How javascript read the property?
    Asweknowwecanreadpropertyvaluefromanobjectasso:constobj={}obj.xxxx;obj[xxxx]; Sowhat'sthedifferencebetweenthosetwo? obj.xECMAScriptwilldoatransforminternallyassuch[[GET]](obj/*objectitself*/,'x'/*pr......
  • [Javascript] Check whether a function is call with new
    The new.target meta-propertyletsyoudetectwhetherafunctionorconstructorwascalledusingthe new operator.Inconstructorsandfunctionsinvokedusingthe new operator, new.target returnsareferencetotheconstructororfunctionthat new wa......