Home > Article > Web Front-end > Can JavaScript Proxies Create Dynamic Getters and Setters for Undefined Properties?
Introduction:
JavaScript offers flexible mechanisms for property access and modification through getters and setters. While it is well-known how to define getters and setters for pre-determined property names, a question arises: is it possible to implement dynamic getters and setters that apply to undefined property names?
Dynamic Getters and Setters using Proxies (ES6 ):
As of ES2015, JavaScript introduced proxies, which allow for the creation of objects that act as "facades" for other objects. This enables the interception and modification of property operations, including getters and setters.
Example:
The following code snippet demonstrates dynamic getters and setters using proxies:
<code class="javascript">"use strict"; if (typeof Proxy == "undefined") { throw new Error("This browser doesn't support Proxy"); } let original = { example: "value", }; let 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(`original.example = ${original.example}`); // "original.example = value" console.log(`proxy.example = ${proxy.example}`); // "proxy.example = VALUE" console.log(`proxy.unknown = ${proxy.unknown}`); // "proxy.unknown = missing" original.example = "updated"; console.log(`original.example = ${original.example}`); // "original.example = updated" console.log(`proxy.example = ${proxy.example}`); // "proxy.example = UPDATED"</code>
In this example:
The above is the detailed content of Can JavaScript Proxies Create Dynamic Getters and Setters for Undefined Properties?. For more information, please follow other related articles on the PHP Chinese website!