繁体   English   中英

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

[英]javascript class variable inside function says undefined ES6

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

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

为什么输出未定义?

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

仅通过声明将变量附加到类上下文不会发生。 你必须明确:

 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(); 

这是指类,您没有在类中声明颜色和类型。 颜色并在您的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();

正如Felix King在评论中所描述的,变量aAuto类的属性不同

 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(); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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