JavaScript 代理是否应该拦截对 Object.Observe 等底层对象的直接更改? [英] Is JavaScript Proxy supposed to intercept direct changes to underlying object like Object.Observe?
问题描述
Object.Observe 的 MDN 表示 Observe 现在已过时,我们应该使用更通用的 Proxy 对象".
MDN for Object.Observe says that Observe is now obsolete and we should use "more general Proxy object instead".
但 Observe 允许拦截现有对象的更改.如果 Proxy 不允许,那么 Proxy API 并不比 Observable API更通用".
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 和 这个问题给出了拦截代理更改的例子对象,但永远不要谈论对底层对象的更改.
MDN for Proxy and this question give examples of intercepting changes to proxy object, but never talk about changes to underlying object.
代理是否应该在当前或未来的 ECMA 标准中拦截对底层对象的更改?
Is Proxy supposed to intercept changes to underlying object in current or future ECMA standard ?
示例:
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 ?
推荐答案
o.p2 = 'v2';//这应该在 ECMA 标准中记录 o, "p2", "v2" 吗?
不,使用那个特定的模式.
No, using that particular pattern.
在Proxy
对象上设置值,在target
对象上设置值.
Set the value at the Proxy
object, and value will be set at target
object.
虽然你也可以在原始对象上定义getter
.
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);
这篇关于JavaScript 代理是否应该拦截对 Object.Observe 等底层对象的直接更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!