class Car {
constructor(name, year) {
this.name = name;
this.year = year;
this.age();
}
age() {
return 99;
}
}
myCar = new Car("Ford", 2014);
document.getElementById("demo").innerHTML =
"My car is " + myCar + " years old.";
//result
My car is [object Object] years old.
why variable myCar did not have value 99 ? instead it contains [object,object]
Taking into account your current code:
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
this.age();
}
age() {
// date = new Date(); // This will not work
let date = new Date(); // This will work
return 99;
}
}
myCar = new Car("Ford", 2014);
document.getElementById("demo").innerHTML =
"My car is " + myCar + " years old.";
myCar
is the object. If you want to return 99 you need to call myCar.age()
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.