Skip to content
Advertisement

JavaScript – this keyword inside an object method

I’m expecting to see the value of 26 returned to the console based on the following code snippet, but I get ‘undefined’. Have I used the ‘this’ keyword incorrectly?

const myDetails = {
  name: "peter",
  birthYear: 1996,
  calcAge: function () {
    this.age = 2022 - this.birthYear;
    return this.age;
  },
  gender: "male"
}

console.log(myDetails.age);

Advertisement

Answer

I change your code a little bit. it should be work now. when you call the function you must need to use function name.

const myDetails = {
    name: "peter",
    birthYear: 1996,
    calcAge: function() {
        this.age = 2022 - this.birthYear;
        return this.age;
    },
    gender: "male"
}
console.log(myDetails.calcAge());//Here 
Advertisement