1

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
1

2 Answers 2

5

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;

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, but this doesn't handle setting value to obj.a directly.
@KesantieluDasefern: No, of course not. To handle that, you'd have to modify 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.
Actually Object.observe was planned for ES7, but they decided to support proxies instead.
-1

Why not to use getters/setters of object?

let ourObj = {
    get a(){
        return this._a;
    }
    set a(val){
        console.log(val);
        this._a = val
    }
}

1 Comment

And what about using getters/setters on already existing properties?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.