Home > Enterprise >  how can i get age from this keyword?
how can i get age from this keyword?

Time:04-16

const meDetails = {
    firstName: 'arman',
    lastName: 'soltani',
    birthday: 1991,
    hasDriverLicense: true,

    calcAge: function () {
        this.age = 2037 - this.birthday;
        return this.age;
    }
};

console.log(meDetails.age);

why the age is not defined??

CodePudding user response:

the variable of named 'age' is not initialized before calling calcAge.

at first you should call calcAge to init meDetailes.age variable at runtime then meDetails.age is valued and you can use it

CodePudding user response:

You need to call calcAge() first to set the age property

meDetails.calcAge();
console.log(meDetails.age);

But you probably want a getter for age.

const meDetails = {
    firstName: 'arman',
    lastName: 'soltani',
    birthday: 1991,
    hasDriverLicense: true,
    
    get age() {
      return 2037 - this.birthday;
    }
};

console.log(meDetails.age);

  • Related