Skip to content
Advertisement

Set undefined javascript property before read

var tr={};
tr.SomeThing='SomeThingElse';
console.log(tr.SomeThing); // SomeThingElse
console.log(tr.Other); // undefined

tr.get=function(what){
    if (tr.hasOwnProperty(what)) return tr[what];
    else return what;
};
tr.get('SomeThing') // SomeThingElse
tr.get('Other') // Other

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:

var o = {
  a: 7,
  get b() {
    return this.a + 1;
  },
  set c(x) {
    this.a = x / 2;
  }
};

console.log(o.a); // 7
console.log(o.b); // 8 <-- At this point the get b() method is initiated.
o.c = 50;         //   <-- At this point the set c(x) method is initiated
console.log(o.a); // 25

or using Object.defineProperties():

var o = { a: 0 };

Object.defineProperties(o, {
    'b': { get: function() { return this.a + 1; } },
    'c': { set: function(x) { this.a = x / 2; } }
});

o.c = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
console.log(o.b); // Runs the getter, which yields a + 1 or 6
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement