var Car = function (year, make, model) {
var printc = "You car is" + this.year + this.make + this.model;
return printc;
}
var mycar = new Car(2010, "Hyundai", "Elantra");
console.log(mycar.printc);
Console.log正在打印undefined。为什么? 我的预期产量是:你的车是2010现代伊兰特
答案 0 :(得分:3)
您返回printc
的值,而不是将其分配给Car
对象。此外,this.year
将始终未定义,除非您手动将它们分配给Car
对象。
尝试以下方法:
var Car = function (year, make, model)
{
this.printc = "You car is" + year + make + model;
}
var mycar = new Car(2010, "Hyundai", "Elantra");
// Correctly returns: You car is2010HyundaiElantra
console.log(mycar.printc);
请注意,不保留空格,因此您可能希望按如下方式更新printc
分配:
this.printc = "You car is " + year + ' ' + make + ' ' + model;
答案 1 :(得分:0)
或者您可以使用ES6类:
'use strict';
class Car {
constructor(year, make, model) {
this.year = year;
this.make = make;
this.model = model;
}
printC() {
return `Your car is ${this.year} ${this.make} ${this.model}`;
}
}
const myCar = new Car(2010, "Hyundai", "Elantra");
document.write(myCar.printC());

答案 2 :(得分:-1)
var Car = function (year, make, model) {
var printc = "You car is" + year + make + model;
return printc;
}
var mycar = Car(2010, "Hyundai", "Elantra");
console.log(mycar);