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
andthis.type
are two different things. – Felix Kling Commented Apr 28, 2017 at 18:41 -
1
this.type
isundefined
because you never setthis.type
to anything. – ibrahim mahrir Commented Apr 28, 2017 at 18:41
3 Answers
Reset to default 2Attaching 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
版权声明:本文标题:javascript class variable inside function says undefined ES6 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744279222a2598568.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论