Is there a way to set the default attribute of a Javascript object such that:
JavaScript
x
4
1
let emptyObj = {};
2
// do some magic
3
emptyObj.nonExistingAttribute // => defaultValue
4
Advertisement
Answer
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:
JavaScript
1
11
11
1
let handler = {
2
get: function(target, name) {
3
return target.hasOwnProperty(name) ? target[name] : 42;
4
}
5
};
6
7
let emptyObj = {};
8
let p = new Proxy(emptyObj, handler);
9
10
p.answerToTheUltimateQuestionOfLife; //=> 42
11
Read more in Mozilla’s documentation on Proxies.