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);
CodePudding user response:
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
CodePudding user response:
Ok I think I've figured it out now...
The object method hasn't been invoked yet! Because function expressions are treated in order (which this object method is... a function expression!) whereas function DECLARATIONS can be added anywhere in the file, but will be automatically "hoisted" to the top.
So in this case, the function needs to be invoked first.
So this works for me, and creates a new key pair of age: 26
const myDetails = {
name: "peter",
birthYear: 1996,
calcAge: function () {
this.age = 2022 - this.birthYear;
return this.age;
},
gender: "male"
}
// invoke the object method
myDetails.calcAge();
console.log(myDetails.age);