Loading lesson path
Concept visual
Start at both ends
A Proxy is a JavaScript object that can wrap other objects. A Proxy lets you control operations on other objects. A Proxy can trap and intercept code when someone is: Reading a property (get) Setting a property (set) Deleting a property (deleteProperty) Checking if a property exists (has) Calling a function (apply) Constructing an object (construct) A Proxy lets you run your own code when someone interacts with an object. A Proxy gan be a middleman between your code and a JavaScript object.
Proxy Syntax const proxy = new Proxy(target, handler);Formula
target - the original object or function handler - an object with trap methodsconst myObject = {name: "Jan"};
const proxy = new Proxy(myObject, {
get(target, prop) {
return target[prop];
}
});A typical Proxy example is logging of object changes.
Logs whenever a property is read or written Logs each get and set operation in real time
Log all changes to all property values: // Create an Object const user = { name: "Jan", age: 40 };
//Create a Proxy const proxy = new Proxy(user, {
get(target, property) {
log("Getting: " + property);
return target[property];
}, set(target, property, value) {
log("Setting: " + property);
return target[property];
}
});
proxy.name = "John";
proxy.age = 42;
let text1 = proxy.name;
let text2 = proxy.age
Proxy with Reflect (Most Common)Logs whenever a property is read or written Uses Reflect.get() and Reflect.set() inside the Proxy handlers get trap uses Reflect.get(target, property, receiver) set trap uses Reflect.set(target, property, value, receiver) Reflect makes the Proxy behavior match the normal object behavior
Log all changes to all property values: // Create an Object const user = { name: "Jan", age: 40 };
// Create a Proxy const proxy = new Proxy(user, {
get(target, property) {
log("Getting: " + property);
// safe forwarding return Reflect.get(target, property);
}, set(target, property, value) {
log("Setting: " + property);
// safe forwarding return Reflect.set(target, property, value);
}
});
proxy.name = "John";
proxy.age = 42;
let text1 = proxy.name;
let text2 = proxy.ageFormula
The flow below is the essence of JavaScript metaprogramming with Proxy + Reflect.Create reactive systems (like Vue.js)