继承的对象上的Javascript代理set()本地属性 [英] Javascript Proxy set() local property on inherited objects
问题描述
根据 MDN ,
handler.set()
可以捕获继承的属性分配:
According to MDN,
handler.set()
can trap Inherited property assignment:
Object.create(proxy)[foo] = bar;
在这种情况下,如何监视和允许对继承的对象进行本地分配?
In which case, how does one both monitor and allow local assignments on inherited objects?
var base = {
foo: function(){
return "foo";
}
}
var proxy = new Proxy(base, {
set: function(target, property, value, receiver){
console.log("called: " + property + " = " + value, "on", receiver);
//receiver[property] = value; //Infinite loop!?!?!?!?!
//target[property] = value // This is incorrect -> it will set the property on base.
/*
Fill in code here.
*/
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.hasOwnProperty("bar")) //true
推荐答案
经过一番思考,我注意到它拦截了3个操作:
After some additional thought, i noticed that it intercepts 3 ops:
属性分配:proxy [foo] = bar和proxy.foo = bar 继承的属性分配:Object.create(proxy)[foo] = bar
Reflect.set()
Property assignment: proxy[foo] = bar and proxy.foo = bar Inherited property assignment: Object.create(proxy)[foo] = bar
Reflect.set()
但不是 Object.defineProperty()
似乎比=运算符还低.
but not Object.defineProperty()
which appears to be even lower level than the = operator.
因此有以下作用:
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")) // true
这篇关于继承的对象上的Javascript代理set()本地属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!