简体   繁体   English

在新键上动态运行Object.defineProperty

[英]Dynamically running Object.defineProperty on new keys

I am using Object.defineProperty to override getter and setter on an object, so that I can listen to all the mutation events. 我正在使用Object.defineProperty重写对象上的getter和setter,以便我可以侦听所有突变事件。

var a = {};
Object.defineProperty(a, key, {
  get: function(){
    ..
  },
  set: function(val){
    ..
  }
}

This works fine, but there's one caveat--I need to know in advance what attributes I want to listen to--which means I need to iterate through all the keys I want to watch in the beginning. 这很好用,但有一个警告-我需要提前知道我想听的属性-这意味着我需要迭代我想看的所有键。

If I wanted to randomly assign a new attribute during runtime like this: 如果我想在运行时像这样随机分配新属性:

a.new_attr=1;

it wouldn't work because I haven't defined the new_attr property yet. 因为我还没有定义new_attr属性,所以它不起作用。

Is there a way to either: 有没有一种方法可以:

  1. dynamically run Object.defineProperty() when I assign the attribute for the first time; 第一次分配属性时,动态运行Object.defineProperty() or 要么
  2. any other way to handle situations like this? 还有其他方法来处理这种情况吗? (Maybe some way to monitor ALL attributes without specifying the keys) (也许可以通过某种方式监视所有属性而无需指定键)

I think what you really want to use is a Proxy . 我认为您真正想要使用的是Proxy Proxies allow you to intercept events such as get and set. 代理允许您拦截诸如get和set之类的事件。

 var obj = { a: 1, b: 2 }; var proxiedObj = new Proxy(obj, { get: function(target, name) { console.log(`get: ${name}`); return target[name]; }, set: function(target, prop, value) { console.log(`set: ${prop}`); target[prop] = value; } }); console.log(proxiedObj.a); console.log(proxiedObj.b); // Notice that it still works even on new properties proxiedObj.c = 3; console.log(proxiedObj.c); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM