返回不按预期工作

时间:2016-02-06 13:23:23

标签: javascript

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现代伊兰特

3 个答案:

答案 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);

jsFiddle Demo

请注意,不保留空格,因此您可能希望按如下方式更新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);