bla*_*ing 3 javascript proxy inheritance
根据MDN,
handler.set()可以捕获继承的属性分配:
Object.create(proxy)[foo] = bar;
Run Code Online (Sandbox Code Playgroud)
在这种情况下,如何同时监视和允许对继承对象进行本地分配?
Object.create(proxy)[foo] = bar;
Run Code Online (Sandbox Code Playgroud)
经过一些额外的思考,我注意到它拦截了 3 个操作:
属性赋值:proxy[foo] = bar 和 proxy.foo = bar 继承属性赋值:Object.create(proxy)[foo] = bar
Reflect.set()
但Object.defineProperty()似乎不是比 = 运算符更低的级别。
因此,以下工作:
var base = {
foo: function(){
return "foo";
}
};
var proxy = new Proxy(base, {
set: function(target, property, value, receiver){
var p = Object.getPrototypeOf(receiver);
Object.defineProperty(receiver, property, { value: value }); // ***
return true;
}
});
var inherited = {};
Object.setPrototypeOf(inherited, Object.create(proxy));
inherited.bar = function(){
return "bar";
};
// Test cases
console.log(base.foo); // function foo
console.log(base.bar); // undefined
console.log(inherited.bar); // function bar
console.log(inherited.hasOwnProperty("bar")) // trueRun Code Online (Sandbox Code Playgroud)