Reputation: 3488
I was wondering if it is possible to override "undefined" for uninitiated keys of an object such that:
var obj={}
console.log(obj.randomKey)
output in console:
0
I am well aware that I "forgot" to initate obj.randomKey. That is in fact my question.
Can I have a default value for any uninitiated key of an object or a class?
If you are curious
The reason I am asking is that I am trying to solve a riddle that allows creation of object with "native" language such as:
const jane = new Thing('Jane')
jane.name // => 'Jane'
// can define boolean methods on an instance
jane.is_a.person
jane.is_a.woman
jane.is_not_a.man
jane.is_a_person // => true
jane.is_a_man // => false
And this is the first strategy I am taking :)
Update: I solved the riddle :) If anyone's interested in trying: https://www.codewars.com/kata/the-builder-of-things/train/javascript
Upvotes: 2
Views: 142
Reputation: 27174
You can't really define a default value, but you can use ES2015 proxies to pretend that they have one:
function createObj(obj) {
return new Proxy(obj, {
get(target, key, receiver) {
if (target[key] === undefined) {
return 0;
}
return Reflect.get(target, key, receiver);
}
});
}
const myObj = createObj({});
console.log(myObj.test); // 0
Nice approach to a language btw!
Upvotes: 5
Reputation: 580
There isn't a way to set this in Javascript - returning undefined for non-existent properties is a part of the core Javascript spec. See the discussion for this similar question. As I suggested there, one approach (though I can't really recommend it) would be to define a global getProperty function:
function getProperty(o, prop) {
if (o[prop] !== undefined) return o[prop];
else return "my default";
}
var o = {
foo: 1
};
getProperty(o, 'foo'); // 1
getProperty(o, 'bar'); // "my default"
But this would lead to a bunch of non-standard code that would be difficult for others to read, and it might have unintended consequences in areas where you'd expect or want an undefined value. Better to just check as you go:
var someVar = o.someVar || "my default";
Upvotes: 1