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
After some additional thought, i noticed that it intercepts 3 ops:
but not
Object.defineProperty()
which appears to be even lower level than the = operator.Thus the following works:
I see two options (maybe):
Store the property in a
Map
, keeping theMap
s for various receivers in aWeakMap
keyed by the receiver. Satisfyget
by checking theMap
and returning the mapping there instead of from the object. (Alsohas
.) Slight problem is that you also need to proxy the receiver (not justbase
) in order to handleownKeys
. So this could be unworkable.Temporarily get the proxy out of the inheritance chain while setting.
Here's that second one: