In traditional JavaScript, getters and setters are defined for specific property names. However, it's possible to create more flexible dynamic getters and setters using proxies introduced in ES2015.
Dynamic getters and setters allow for property access and modification without explicit definitions. Here's how to implement them using proxies:
"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);
// Modify the value here before returning
return rv;
}
// Define default behavior for unknown properties
return "missing";
}
});
With the above proxy in place, property access and modification can be performed dynamically:
console.log(`proxy.example = ${proxy.example}`); // "proxy.example = VALUE"
console.log(`proxy.unknown = ${proxy.unknown}`); // "proxy.unknown = missing"
Proxies are supported in modern browsers such as Chrome, Firefox, and Safari. However, for older browsers that do not support proxies, a workaround can be implemented using the dynamic getter/setter syntax without proxies.
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