Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Proxy lets you intercept and customize operations on objects. Reflect provides methods for interceptable operations. Together they enable powerful meta-programming!
const user = {
name: 'Alice',
age: 25
};
console.log(user.name); // Alice
user.age = 26;
// No way to intercept operations
// Can't validate, log, or customizeconst user = { name: 'Alice', age: 25 };
const proxy = new Proxy(user, {
get(target, prop) {
console.log(`Reading ${prop}`);
return target[prop];
},
set(target, prop, value) {
console.log(`Writing ${prop} = ${value}`);
target[prop] = value;
return true;
}
});
console.log(proxy.name); // Reading name, Alice
proxy.age = 26; // Writing age = 26Intercepting get and set operations
Intercepts property accessobj.prop or obj['prop']
Intercepts property assignmentobj.prop = value
Intercepts in operator'prop' in obj
Intercepts deletiondelete obj.prop
Intercepts function callsfunc(...args)
Intercepts new operatornew Constructor(...args)
has, deleteProperty, apply, and more
// Reflect methods match proxy traps
const obj = { x: 1, y: 2 };
// Reflect.get = obj.x
console.log(Reflect.get(obj, 'x')); // 1
// Reflect.set = obj.x = value
Reflect.set(obj, 'x', 10);
console.log(obj.x); // 10
// Reflect.has = 'prop' in obj
console.log(Reflect.has(obj, 'x')); // true
// Reflect.deleteProperty = delete obj.prop
Reflect.deleteProperty(obj, 'y');
console.log(obj); // { x: 10 }
// Using in proxy (recommended!)
const proxy = new Proxy(obj, {
get(target, prop) {
console.log(`Reading ${prop}`);
return Reflect.get(target, prop); // Use Reflect!
},
set(target, prop, value) {
console.log(`Writing ${prop}`);
return Reflect.set(target, prop, value); // Use Reflect!
}
});Meta operations with Reflect
Track changes with Proxy (like Vue 3 reactivity)
Python-style negative indexes with Proxy
Track all property access and modifications
Wrap objects to intercept operations
13 traps: get, set, has, delete, apply, etc.
Built-in meta operations
Mirrors proxy traps (use in handlers!)
Validation, logging, reactivity
Default values, access control
Vue 3 reactivity uses Proxy
MobX, Immer also leverage Proxy