0
Default keys for objects?
For example, I have this object: var object = { first: 1, second: 2 } Now I want to set key second to standard, so every time I access the object with simply 'object' or with a key that doesn't exist, it should return second. Is this possible? Thanks in advance
1 Odpowiedź
+ 2
Use Proxy with getter to achieve it
var object = {
first: 1,
second: 2,
get: function(target, name) {
return this.hasOwnProperty(name) ? this[name]:0; //default
}
}
var obj = new Proxy({}, object);
console.log(obj.zero);
console.log(obj.first);
console.log(obj.second);
console.log(obj.third);
https://code.sololearn.com/W65Bp6xVsfLj/?ref=app