Home > Web Front-end > JS Tutorial > Can JavaScript Implement Dynamic Getters and Setters for Unpredictable Properties?

Can JavaScript Implement Dynamic Getters and Setters for Unpredictable Properties?

Barbara Streisand
Release: 2024-10-29 18:04:02
Original
211 people have browsed it

 Can JavaScript Implement Dynamic Getters and Setters for Unpredictable Properties?

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:

<code class="js">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"</code>
Copy after login

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.

The above is the detailed content of Can JavaScript Implement Dynamic Getters and Setters for Unpredictable Properties?. 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