函数内部的javascript类变量表示未定义的ES6

时间:2017-04-28 18:39:21

标签: javascript es6-class

2D

为什么输出未定义?

车型=未定义且颜色=未定义

3 个答案:

答案 0 :(得分:2)

将变量附加到类上下文并不是通过声明来实现的。你必须明确:



class Auto {
  printauto() {
    this.type = "2 wheeler"; // explicitly attach to `this`
    this.color = "green";    // same here
    console.log("Car type is="+this.type+" "+" and color="+this.color);
 }
}

new Auto().printauto();




构造函数通常是进行此类初始化的最佳位置:



class Auto {
  constructor() {
    this.type = "2 wheeler"; // explicitly attach to `this`
    this.color = "green";    // same here
  }
  printauto() {
    console.log("Car type is="+this.type+" "+" and color="+this.color);
 }
}

new Auto().printauto();




答案 1 :(得分:1)

这是指类,您没有在类中声明颜色和类型。颜色并在您的printauto方法范围内。要么在课堂上宣布它们,要么就这样做

console.log("Car type is="+type+" "+" and color="+color);

在课堂上宣布

class Auto {
    this.type = "2 wheeler";
    this.color = "green";

    printauto() {
        console.log("Car type is=" + this.type + " " + " and color=" + this.color);
    }
}
var a = new Auto();
a.printauto();

答案 2 :(得分:0)

如Felix King在评论中所述,变量a与类Auto

的属性不同



class Auto {
  printauto() {
    var type = "2 wheeler";
    var color = "green";
    console.log("Car type is="+ type+" "+" and color="+color);
 }
}

var a = new Auto();
a.printauto();