const list = {
name: 'Harry Potter',
birthYear: 1995,
calcAge: function () {
this.age = 2002 - this.birthYear;
return this.age;
}
};
console.log(list.age);
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);
Call your function. list.calcAge()
You can print it like this console.log(list.calcAge())
You were close though!!
const list = { name: 'Harry Potter', birthYear: 1995, calcAge() { this.age = 2002 - this.birthYear; return this.age; }, }; console.log(list.calcAge());
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
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.