Home > Web Front-end > JS Tutorial > body text

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

Linda Hamilton
Release: 2024-11-02 02:58:30
Original
384 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!