MENU
Handlers for Operators
Each method recognized in the handler for Proxy has a corresponding method with the same name in Reflect. Implementing such a Proxy method affects the corresponding Reflect method.
.get()
A trap for getting property values, eg. o[p], o.p.
.set()
A trap for setting property values, eg. o.p = X.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
var handler = {
get: function(target, prop, receiver) {
return target[prop]*2;
},
set: function(target, prop, value, receiver) {
target[prop]=value+100;
return true;
}};var o = {a:3};var p = new Proxy(o, handler);console.log(o.a); // 3console.log(p.a); // 6p.b = p.a; // (changing p changes o)console.log(o.b); // 106console.log(p.b); // 212 ... (106*2)o.b = o.a; // (changing o also changes p)console.log(o.b); // 3console.log(p.b); // 6 ... (3*2)var p = new Proxy(o,{ // (restore to default behaviours for these two handlers)
get: Reflect.get,
set: Reflect.set});p.b = p.a;console.log(p.b); // 3
</script></body><html>
.has()
A trap for the in operator.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
var p = new Proxy({}, {
has: function(target, prop) {
return true;
}});console.log('a' in p); // trueconsole.log(Reflect.has(p,'a')); // true
… (affects the corresponding Reflect method)p = new Proxy({},Reflect); // (restores all default behaviours)console.log('a' in p); // false
</script></body><html>
.deleteProperty()
A trap for the delete operator.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
var p = new Proxy({a:3}, {
deleteProperty: function(target, prop) {
if (prop in target){
delete target[prop];
console.log('property removed: ' + prop);
return true;
} else {
console.log('property not found: ' + prop);
return false;
}
}});delete p.a; // property removed: adelete p.a; // property not found: a
</script></body><html>