Can JavaScript Implement Dynamic Getters/Setters?
Dynamic getters and setters allow JavaScript objects to handle property access and modification beyond predefined properties. While earlier JavaScript techniques employed specific getters and setters for known properties, this article explores the possibility of implementing catch-all getters and setters for any undefined properties.
ES2015 Proxy: A Dynamic Solution
ES2015 introduced JavaScript proxies, which enable the creation of objects that serve as intermediaries for other objects. This capability opens up dynamic getters and setters:
<code class="js">const original = { example: "value", }; const proxy = new Proxy(original, { get(target, name, receiver) { if (Reflect.has(target, name)) { let rv = Reflect.get(target, name, receiver); if (typeof rv === "string") { rv = rv.toUpperCase(); } return rv; } return "missing"; }, }); console.log(`proxy.example = ${proxy.example}`); // "proxy.example = VALUE" console.log(`proxy.unknown = ${proxy.unknown}`); // "proxy.unknown = missing"</code>
In this example, the proxy object intercepts property access for the original object. When accessing a string property, the proxy converts it to uppercase and returns it; for unknown properties, it returns "missing" instead of undefined.
This implementation is cross-browser compatible if the browser supports ES2015 (ES6). For older browsers, consider using polyfills or alternative techniques. Proxies provide a flexible solution for dynamic getters and setters, enabling efficient property handling and property introspection without modifying the original object.
The above is the detailed content of Can JavaScript Implement Dynamic Getters and Setters for Unpredictable Properties?. For more information, please follow other related articles on the PHP Chinese website!