JavaScript Meta Programming
Learn about Proxies and Reflection.
1. Proxies
A Proxy
object allows you to intercept and define custom behavior for fundamental language operations (e.g., property lookup, assignment, enumeration, function invocation, etc.).
JavaScript Code
Live JavaScript representation with highlighted changes
const handler = {get: function(target, name) {return name in target ? target[name] : 42;}};const p = new Proxy({}, handler);p.a = 1;console.log(p.a, p.b);
2. Reflection
Reflect
is a built-in object that provides methods for interceptable JavaScript operations. The methods are the same as those of the proxy handlers.
JavaScript Code
Live JavaScript representation with highlighted changes
const duck = {name: 'Maurice',color: 'white',greeting: function() {console.log(`Quaaaack! My name is ${this.name}`)}}Reflect.get(duck, 'color'); // whiteReflect.has(duck, 'color'); // true
Console Output