简体   繁体   中英

constructor call a member function that return a value in javascript

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.";
  1. myCar is the object. If you want to return 99 you need to call myCar.age()
  2. mind that the "age" of a car depends on the current date. My today's 13 year old car can be 14 tomorrow. And with year alone you cannot be fully exact on this.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM