I am creating an object where I have a name, age, profession and a method called statement. Here is the code:
let objOfPerson = {
name: 'Siddhu',
age: 11,
profession: this.age >= 18 ? 'programmer' : 'student',
statement: function () {
return `${this.name} is a ${this.age} year old ${this.profession}.`;
},
};
console.log(objOfPerson)
Everything is pretty much what I expected, except the value of profession. I was confused at first, but now I think I understand the issue - I can only use the this
keyword when it is in a function (or method). So then I tried to change the this
to objOfPerson
, but then I got an error saying that I couldn't access the value before initialization. So my question is this: How do I access the correct value without hardcoding it?
Any help is appreciated.
EDIT(s):
I know that I could fix this whole thing by turning it into a method, but I don't really want to. Also, the question that my one has been associated with gives an answer that is too complex for my level - I'd like simple answers that I can understand.