Is it possible to implement dynamic getters/setters in JavaScript?

This changed as of the ES2015 (aka “ES6”) specification: JavaScript now has proxies. Proxies let you create objects that are true proxies for (facades on) other objects. Here’s a simple example that turns any property values that are strings to all caps on retrieval, and returns "missing" instead of undefined for a property that doesn’t exist:

"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);
            if (typeof rv === "string") {
                rv = rv.toUpperCase();
            }
            return rv;
        }
        return "missing";
      }
});
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"

Operations you don’t override have their default behavior. In the above, all we override is get, but there’s a whole list of operations you can hook into.

In the get handler function’s arguments list:

  • target is the object being proxied (original, in our case).
  • name is (of course) the name of the property being retrieved, which is usually a string but could also be a Symbol.
  • receiver is the object that should be used as this in the getter function if the property is an accessor rather than a data property. In the normal case this is the proxy or something that inherits from it, but it can be anything since the trap may be triggered by Reflect.get.

This lets you create an object with the catch-all getter and setter feature you want:

"use strict";
if (typeof Proxy == "undefined") {
    throw new Error("This browser doesn't support Proxy");
}
let obj = new Proxy({}, {
    get(target, name, receiver) {
        if (!Reflect.has(target, name)) {
            console.log("Getting non-existent property '" + name + "'");
            return undefined;
        }
        return Reflect.get(target, name, receiver);
    },
    set(target, name, value, receiver) {
        if (!Reflect.has(target, name)) {
            console.log(`Setting non-existent property '${name}', initial value: ${value}`);
        }
        return Reflect.set(target, name, value, receiver);
    }
});

console.log(`[before] obj.example = ${obj.example}`);
obj.example = "value";
console.log(`[after] obj.example = ${obj.example}`);

The output of the above is:

Getting non-existent property 'example'
[before] obj.example = undefined
Setting non-existent property 'example', initial value: value
[after] obj.example = value

Note how we get the “non-existent” message when we try to retrieve example when it doesn’t yet exist, and again when we create it, but not after that.


Answer from 2011 (obsoleted by the above, still relevant to environments limited to ES5 features like Internet Explorer):

No, JavaScript doesn’t have a catch-all property feature. The accessor syntax you’re using is covered in Section 11.1.5 of the spec, and doesn’t offer any wildcard or something like that.

You could, of course, implement a function to do it, but I’m guessing you probably don’t want to use f = obj.prop("example"); rather than f = obj.example; and obj.prop("example", value); rather than obj.example = value; (which would be necessary for the function to handle unknown properties).

FWIW, the getter function (I didn’t bother with setter logic) would look something like this:

MyObject.prototype.prop = function(propName) {
    if (propName in this) {
        // This object or its prototype already has this property,
        // return the existing value.
        return this[propName];
    }

    // ...Catch-all, deal with undefined property here...
};

But again, I can’t imagine you’d really want to do that, because of how it changes how you use the object.

Leave a Comment