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?
JavaScript
x
12
12
1
const myDetails = {
2
name: "peter",
3
birthYear: 1996,
4
calcAge: function () {
5
this.age = 2022 - this.birthYear;
6
return this.age;
7
},
8
gender: "male"
9
}
10
11
console.log(myDetails.age);
12
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.
JavaScript
1
11
11
1
const myDetails = {
2
name: "peter",
3
birthYear: 1996,
4
calcAge: function() {
5
this.age = 2022 - this.birthYear;
6
return this.age;
7
},
8
gender: "male"
9
}
10
console.log(myDetails.calcAge());//Here
11