0

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.

  • Basically, you cannot do that. The linked duplicate has many suggestions. – Pointy Oct 27 '22 at 13:38
  • I guess, but I'm really confused as to how that works - I want a solution that makes sense to me - plus, I'm not that advanced. –  Oct 27 '22 at 13:39
  • https://stackoverflow.com/questions/41496958/this-does-not-work-properly-in-another-event-im-clueless-as-to-why/41496969#41496969 – Scott Marcus Oct 27 '22 at 13:40
  • "_I want a solution that makes sense to me_" - The linked duplicate has 30 answers. Surely there is one that makes sense to you? [T.J. Crowder's answer here](https://stackoverflow.com/a/10766107/479156) is as simple as it is going to get. – Ivar Oct 27 '22 at 13:41
  • Thanks - I hadn't considered adding the property after initialization –  Oct 27 '22 at 13:46
  • You can achieve the required functionality by writing: `get statement() {` instead of `statement: function(){` – Pascal Stockert Oct 27 '22 at 13:50
  • Yeah - well I don't have a clue about how get works. –  Oct 27 '22 at 13:51

0 Answers0