Set default value of Javascript object attributes

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.

Leave a Comment