admin管理员组

文章数量:1401214

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

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

Share Improve this question edited Apr 28, 2017 at 18:43 Dom 40.5k12 gold badges54 silver badges82 bronze badges asked Apr 28, 2017 at 18:39 YogeshYogesh 3311 gold badge4 silver badges10 bronze badges 2
  • 2 Because a variable is not the same as a property. var type and this.type are two different things. – Felix Kling Commented Apr 28, 2017 at 18:41
  • 1 this.type is undefined because you never set this.type to anything. – ibrahim mahrir Commented Apr 28, 2017 at 18:41
Add a ment  | 

3 Answers 3

Reset to default 2

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

本文标签: javascript class variable inside function says undefined ES6Stack Overflow