How can I define a default getter and setter using ECMAScript 5?

Manuel picture Manuel · Jun 24, 2010 · Viewed 8.6k times · Source

How can I specify a default getter for a prototype? With default getter I mean a function that is called if obj.undefinedProperty123 is called.

I tried Object.prototype.get = function(property) {..} but this is not called in this case.

Answer

apsillers picture apsillers · Sep 29, 2014

In ECMAScript 5, you can only intercept get/set operations on specific named properties (not universally all properties) via Object.defineProperty:

Object.defineProperty(someObj, "someProp", {
    get: function() {
        console.log("you tried to get someObj.someProp");
        return "foo";
    }
});

Here, the get function will run any time code tries to read someObj.someProp.

In the upcoming ECMAScript 6 draft, this will be possible via proxies. A proxy has an underlying target object and set/get functions. Any time a set or get operation happens on any of a proxy's properties, the appropriate function runs, taking as arguments the proxy's target object, property name used, and the value used in a set attempt.

var proxyHandler = {
    get: function(obj, name){
        console.log("you're getting property " + name);
        return target[name];
    },
    set: function(obj, name, value) {
        console.log("you're setting property " + name);
        target[name] = value;
    }
}

var underlyingObj = {};

// use prox instead of underlyingObj to use get/set interceptor functions
var prox = new Proxy(underlyingObj, proxyHandler);

Here, setting to getting property values on prox will cause the set/get functions to run.