JavaScript
x
12
12
1
var tr={};
2
tr.SomeThing='SomeThingElse';
3
console.log(tr.SomeThing); // SomeThingElse
4
console.log(tr.Other); // undefined
5
6
tr.get=function(what){
7
if (tr.hasOwnProperty(what)) return tr[what];
8
else return what;
9
};
10
tr.get('SomeThing') // SomeThingElse
11
tr.get('Other') // Other
12
Is there any way to make tr.Other or tr[‘Other’] and all other undefined properties of the object to return its name instead undefined?
Advertisement
Answer
You could define a getter for your property, either using object initializers:
JavaScript
1
15
15
1
var o = {
2
a: 7,
3
get b() {
4
return this.a + 1;
5
},
6
set c(x) {
7
this.a = x / 2;
8
}
9
};
10
11
console.log(o.a); // 7
12
console.log(o.b); // 8 <-- At this point the get b() method is initiated.
13
o.c = 50; // <-- At this point the set c(x) method is initiated
14
console.log(o.a); // 25
15
or using Object.defineProperties()
:
JavaScript
1
10
10
1
var o = { a: 0 };
2
3
Object.defineProperties(o, {
4
'b': { get: function() { return this.a + 1; } },
5
'c': { set: function(x) { this.a = x / 2; } }
6
});
7
8
o.c = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
9
console.log(o.b); // Runs the getter, which yields a + 1 or 6
10