-3

I am new to javascript oop i have been trying to get the desired value but it gives me undefined

class person {
  constructor(isGreat, brain, personality) {
    this.isGreat = isGreat;
    this.brain = brain;
    this.personality = personality;
  }
  getDetails(req) {
    this.req = req;

    let dic = {
      isGreat: this.isGreat,
      brain: `they have ${this.brain} brain`,
      personality: `they have ${this.personality} personality`,
    };

    return dic.req;
  }
}

let person0 = new person(true, "massive", "great");
console.log(person0.getDetails("isGreat"));

req can get read but dic.req shows undefined

The problem is console.log shows undefined.

AG_1380
  • 552
  • 5
  • 12
Taha
  • 37
  • 1
  • 4

2 Answers2

1

dic doesn't have a req property. If you want to get a property whose name is stored in req variable, use the following syntax:

dic[req]

Just like accessing array members. In fact, a.b and a['b'] are equivalent in JavaScript.

BTW: The assignment this.req = req is not necessary.

Marcin Szwarc
  • 569
  • 3
  • 13
0

You are returning the req property of your object, not the property with the key stored inside req. You need to use square brackets to get the index stored inside req.

return dic[req]

This is because it gets parsed as dic['isgreat'] rather than dic['req'].

louisi9
  • 26
  • 2