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

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


2013 and 2015 Update (see below for the original answer from 2011):

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:

"use strict";if (typeof Proxy == "undefined") {    throw new Error("This browser doesn't support Proxy");}let original = {    "foo": "bar"};let proxy = new Proxy(original, {    get(target, name, receiver) {        let rv = Reflect.get(target, name, receiver);        if (typeof rv === "string") {            rv = rv.toUpperCase();        }        return rv;      }});console.log(`original.foo = ${original.foo}`); // "original.foo = bar"console.log(`proxy.foo = ${proxy.foo}`);       // "proxy.foo = BAR"