简体   繁体   中英

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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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