What works:
Having a JavaScript object like e.g.
var obj = {
var1: "one"
};
I can call it like one of the following ways:
console.log(obj.var1);
console.log(obj['var1']);
What fails:
This one would fail:
console.log(obj.var2);
because var2
is no property/variable of the anonymous object, thus, undefined
is printed in the console log.
My goal:
What I would love to have is a fallback function that would be called automatically when no matching property/variable is found.
E.g. something like:
var obj = {
var1: "one",
__propertyNotFound__: function (name) {
if ( name=="var2" ) return "two";
else return null;
}
};
Unfortunately I found no whatsoever close solution.
My question:
Being a rather JavaScript newbie, is my question a dumb question and the complete wrong approach or could it make sense and is there actually a solution to solve this?