Home > OS >  this keyword within a function of an object not returning expected value
this keyword within a function of an object not returning expected value

Time:08-06

I am new to coding and learning about the this keyword, I'm expecting the function in the stephen object to perform the calculation given to it (2022-1995) and for that result to show, but it seems like the this keyword is not defined and I do not know why after trying to fix it for hours.

const stephen = {
  firstName: 'Stephen',
  lastName: 'McColgan',
  job: 'Admin',
  friends: ['Chris', 'Simon', 'Thea', 'N/A'],
  hasDriversLicense: true,
  age: 1995,
  calcAge: function() {
    this.birthYear = 2022 - this.age;
    return this.birthYear;
  }
};

console.log(stephen.age);
console.log(stephen.birthYear);

CodePudding user response:

You are not the calling the calcAge() function before displaying the age. So It is returning undefined cause this.birthYear will be initialize when you will call the function. So first you should call calcAge() function and the display the age.


In your case birthYear and age got swapped. Here is working code:

const stephen = {
  firstName: 'Stephen',
  lastName: 'McColgan',
  job: 'Admin',
  friends: ['Chris', 'Simon', 'Thea', 'N/A'],
  hasDriversLicense: true,
  birthYear: 1995,
  calcAge: function() {
    this.age = 2022 - this.birthYear;
    return this.age;

  }
};

stephen.calcAge();

console.log(stephen.age);

  • Related