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.
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);
console.log(p.a);
p.b = p.a; // (changing p changes o)
console.log(o.b);
console.log(p.b);
o.b = o.a; // (changing o also changes p)
console.log(o.b);
console.log(p.b);
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
6
106
212
3
6
3
.has()
A trap for the in operator.
var p = new Proxy({}, {
has: function(target, prop) {
return true;
}
});
console.log('a' in p);
console.log(Reflect.has(p, 'a'));
// … (affects the corresponding Reflect method)
p = new Proxy({}, Reflect); // (restores all default behaviours)
console.log('a' in p);true
true
false
.deleteProperty()
A trap for the delete operator.
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;
delete p.a;property removed: a
property not found: a