【发布时间】:2017-01-09 07:47:18
【问题描述】:
根据MDN,
handler.set()可以trap Inherited property assignment:
Object.create(proxy)[foo] = bar;
在这种情况下,如何监控和允许对继承对象进行本地分配?
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
【问题讨论】:
标签: javascript inheritance proxy