如何在Javascript(ES6)中正确定义子类构造函数?

时间:2017-01-25 13:57:17

标签: javascript class this subclass

我在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类中定义。为什么会这样?

1 个答案:

答案 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/

更深入: