ES6 Proxies: Metaprogramming Powerhouse in JavaScript
Key Concepts:
ES6 proxies enable metaprogramming by intercepting object property access. A proxy acts as an intermediary between your code and the target object. This involves three key elements:
Illustrative Example:
Let's create a proxy that intercepts property access:
const target = { a: 1, b: 2, c: 3 }; const handler = { get: (target, prop) => (prop in target ? target[prop] : 42), // Default to 42 if property doesn't exist }; const proxy = new Proxy(target, handler); console.log(proxy.a); // 1 console.log(proxy.b); // 2 console.log(proxy.d); // 42
This proxy returns the original value if the property exists; otherwise, it returns 42.
Advanced Example: Controlled Property Setting
We can enhance the proxy to restrict property assignments:
const handler = { get: (target, prop) => (prop in target ? target[prop] : 42), set: (target, prop, value) => { if (prop.length === 1 && prop >= 'a' && prop <= 'z') { target[prop] = value; return true; } else { throw new Error(`Invalid property: ${prop}`); } }, }; const proxy = new Proxy({}, handler); // Start with an empty object proxy.a = 10; // Allowed proxy.b = 20; // Allowed try { proxy.AB = 30; // Throws an error } catch (e) { console.error(e); }
This example only allows single-character properties (a-z) to be set.
Available Proxy Traps:
Beyond get
and set
, numerous traps offer fine-grained control:
construct
: Intercepts new
operator calls.apply
: Intercepts function calls.deleteProperty
: Intercepts property deletion.has
: Intercepts in
operator checks.ownKeys
: Intercepts property enumeration.Practical Applications:
Browser Compatibility and Limitations:
While widely supported in modern browsers and Node.js, ES6 proxies lack complete cross-browser compatibility (especially older browsers). Crucially, they cannot be polyfilled due to their fundamental nature.
Frequently Asked Questions (FAQs):
The provided FAQs are already comprehensive and well-structured. No further additions are needed.
The above is the detailed content of ES6 in Action: How to Use Proxies. For more information, please follow other related articles on the PHP Chinese website!