A full list of available "traps" can be found on MDN - Proxy - "Methods of the handler object".
This proxy simply appends the string " went through proxy"
to every string property set on the target object
.
let object = {};
let handler = {
set(target, prop, value){ // Note that ES6 object syntax is used
if('string' === typeof value){
target[prop] = value + " went through proxy";
}
}
};
let proxied = new Proxy(object, handler);
proxied.example = "ExampleValue";
console.log(object);
// logs: { example: "ExampleValue went trough proxy" }
// you could also access the object via proxied.target
To influence property lookup, the get
handler must be used.
In this example, we modify property lookup so that not only the value, but also the type of that value is returned. We use Reflect to ease this.
let handler = {
get(target, property) {
if (!Reflect.has(target, property)) {
return {
value: undefined,
type: 'undefined'
};
}
let value = Reflect.get(target, property);
return {
value: value,
type: typeof value
};
}
};
let proxied = new Proxy({foo: 'bar'}, handler);
console.log(proxied.foo); // logs `Object {value: "bar", type: "string"}`
let proxied = new Proxy(target, handler);
Parameter | Details |
---|---|
target | The target object, actions on this object (getting, setting, etc...) will be routed trough the handler |
handler | An object that can define "traps" for intercepting actions on the target object (getting, setting, etc...) |