Home  >  Article  >  Web Front-end  >  Can JavaScript Proxies Enable Dynamic Getters & Setters for Any Property?

Can JavaScript Proxies Enable Dynamic Getters & Setters for Any Property?

Linda Hamilton
Linda HamiltonOriginal
2024-11-02 02:58:30386browse

Can JavaScript Proxies Enable Dynamic Getters & Setters for Any Property?

Implementing Dynamic Getters and Setters in JavaScript

Question:

While standard JavaScript allows for the creation of getters and setters for specific properties, is it possible to create catch-all getters and setters that handle any property name not explicitly defined?

Answer:

Yes, JavaScript support for dynamic getters and setters was introduced in the ES2015 specification through the use of proxies. Proxies create wrapper objects that intercept property access and modifications, allowing for custom behavior.

Implementation:

Here's an example proxy that converts string property values to uppercase and returns "missing" for undefined properties:

<code class="js">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";
    }
});</code>

Usage:

<code class="js">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>

Note:

Proxy support is considered cross-browser compatible and is supported by all major modern browsers.

The above is the detailed content of Can JavaScript Proxies Enable Dynamic Getters & Setters for Any Property?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn