我在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类中定义。为什么会这样?
答案 0 :(得分:3)
在子类中使用this
之前'构造函数,你必须调用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/
更深入: