javascript

Set default value of Javascript object attributes


Is there a way to set the default attribute of a Javascript object such that:

let emptyObj = {};
// do some magic
emptyObj.nonExistingAttribute // => defaultValue

Solution

  • Since I asked the question several years ago things have progressed nicely.

    Proxies are part of ES6. The following example works in Chrome, Firefox, Safari and Edge:

    let handler = {
      get: function(target, name) {
        return target.hasOwnProperty(name) ? target[name] : 42;
      }
    };
    
    let emptyObj = {};
    let p = new Proxy(emptyObj, handler);
    
    p.answerToTheUltimateQuestionOfLife; //=> 42
    

    Read more in Mozilla's documentation on Proxies.