函数内部的javascript类变量表示未定义的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();
标签:es6-class,javascript 来源: https://codeday.me/bug/20191111/2019789.html