'I don't know why this 'this' method doesn't work?
const list = {
name: 'Harry Potter',
birthYear: 1995,
calcAge: function () {
this.age = 2002 - this.birthYear;
return this.age;
}
};
console.log(list.age);
Solution 1:[1]
Call your function. list.calcAge() You can print it like this console.log(list.calcAge()) You were close though!!
Solution 2:[2]
You are storing a function, not calling it that's why it should print you undefined. To fix it you should call it with list.calcAge().
Your code works and this.age = 2002 - this.birthYear creates the property you want, you just need to call it before using it.
const list = {
name: 'Harry Potter',
birthYear: 1995,
calcAge: function () {
this.age = 2002 - this.birthYear;
return this.age;
}
};
list.calcAge()
console.log(list.age);
Solution 3:[3]
const list = {
name: 'Harry Potter',
birthYear: 1995,
calcAge() {
this.age = 2002 - this.birthYear;
return this.age;
},
};
console.log(list.calcAge());
Solution 4:[4]
Try this. It will work.
const list = {
name: 'Harry Potter',
birthYear: 1995,
calcAge: function () {
this.age = 2002 - this.birthYear;
return this.age;
},
};
console.log(list.calcAge());
Try calling list.calcAge() in your console
Solution 5:[5]
the calcAge is function property so you must be treated as a function list.calcAge()
const list = {
name: 'Harry Potter',
birthYear: 1995,
calcAge: function () {
this.age = 2002 - this.birthYear;
return this.age;
}
};
document.getElementById("name").innerHTML = list.name;
document.getElementById("birthYear").innerHTML = list.birthYear;
document.getElementById("age").innerHTML = list.calcAge();
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p id="name"></p>
<p id="birthYear"></p>
<p id="age"></p>
</body>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | mstephen19 |
| Solution 4 | Vishnu S Babu |
| Solution 5 | Mazen Alhrazi |

