Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading