[英]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: 有没有一种方法可以:
Object.defineProperty()
when I assign the attribute for the first time; Object.defineProperty()
; or 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.