Is JavaScript Proxy supposed to intercept direct c

2019-01-29 12:21发布

MDN for Object.Observe says that Observe is now obsolete and we should use "more general Proxy object instead".

But Observe allowed to intercept changes on existing object. If Proxy does not allow then Proxy API is not "more general" than Observable API.

MDN for Proxy and this question give examples of intercepting changes to proxy object, but never talk about changes to underlying object.

Is Proxy supposed to intercept changes to underlying object in current or future ECMA standard ?

Example:

let o = {};
let p = new Proxy(o, { set: (target, prop, val)=> console.log(target, prop, val) });
p.p1 = 'v1'; // this will log o, "p1", "v1"
o.p2 = 'v2'; // is this supposed to log o, "p2", "v2" in ECMA standard ?

1条回答
Explosion°爆炸
2楼-- · 2019-01-29 12:44

o.p2 = 'v2'; // is this supposed to log o, "p2", "v2" in ECMA standard ?

No, using that particular pattern.

Set the value at the Proxy object, and value will be set at target object.

Though you can also define getter at original object.

var obj = {
  get getProp() {
    return "obj getter: " + (this["x"] || void 0);
  }
};

var proxy = new Proxy(obj, {
  set: function(obj, prop, newval) {
    var oldval = obj[prop];
    console.log("set", oldval, obj, prop, newval);
    obj[prop] = newval;
  }, get: function(obj, prop) {
       console.log("get", obj, prop);
  }
});

proxy.x = 1;

console.log(obj.x);

console.log(obj.getProp);

查看更多
登录 后发表回答