Can I use ES6 Proxy to observe object, getting and setting properties etc? For example:
var obj = {a: 1; b: 2};
obj.a = 3; // I need to catch this setting, like a Object.watch() in Firefox
Can I use ES6 Proxy to observe object, getting and setting properties etc? For example:
var obj = {a: 1; b: 2};
obj.a = 3; // I need to catch this setting, like a Object.watch() in Firefox
Yes, that's part of what they're for. The trap you're looking for is called set:
let obj = {a: 1, b: 2};
let p = new Proxy(obj, {
set(target, name, value) {
console.log("set " + name + " to " + value);
target[name] = value;
}
});
p.a = 3;
obj.a directly.obj (e.g., install a getter/setter combination), and it would be property-specific. AFAIK, there are no plans for Object.watch-like functionality; too much of a performance impact relative to utility.Why not to use getters/setters of object?
let ourObj = {
get a(){
return this._a;
}
set a(val){
console.log(val);
this._a = val
}
}