简体   繁体   中英

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.

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.

Is there a way to either:

  1. dynamically run Object.defineProperty() when I assign the attribute for the first time; 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 . Proxies allow you to intercept events such as get and 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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