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:
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"
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3