如何在Javascript(ES6)中正确定义子类构造函数?
作者:互联网
我很难为JS中的子类构造一个构造函数.类的构造函数可以正常工作!
//defining base class State
class State {
constructor(){
this.someText = "someText";
}
start(){
}
update(){
}
exit(){
}
}
//defining subclass preloadState
class preloadState extends State{
constructor(){
this.ball = "red";
}
start(){
console.log(this.ball);
}
}
var state = new preloadState;
state.start();
}
运行代码时,出现错误this.ball未在preloadState类中定义.为什么会这样?
解决方法:
在子类的构造函数中使用此函数之前,必须调用super:
class preloadState extends State {
constructor() {
super();
this.ball = "red";
}
}
例如:https://jsfiddle.net/n0ek40ph/
另一个选择是不重写构造函数:
class preloadState extends State {
start() {
this.ball = "red";
console.log(this.ball);
}
}
示例:https://jsfiddle.net/n0ek40ph/3/
更深入:
> http://exploringjs.com/es6/ch_classes.html
> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
标签:subclass,this,javascript,class 来源: https://codeday.me/bug/20191111/2022397.html