简体   繁体   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();

why is output undefined? 为什么输出未定义?

Car type is=undefined and color=undefined 汽车类型=未定义且颜色=未定义

Attaching a variable to the class context doesn't happen just by declaring it. 仅通过声明将变量附加到类上下文不会发生。 You have to be explicit: 你必须明确:

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

The constructor is usually the best place for such initialization: 构造函数通常是进行此类初始化的最佳位置:

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

This refer to class and you don't have color and type declared in your class. 这是指类,您没有在类中声明颜色和类型。 The color and are scoped inside your printauto method. 颜色并在您的printauto方法范围内。 either you declare them in your class or just do this 要么在课堂上宣布它们,要么就是这样做

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

By declaring in class 通过在课堂上宣布

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

As described by Felix King in comment, variable a is not the same as properties of class Auto 正如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