【问题标题】:How to properly define subclass constructors in Javascript (ES6)?如何在 Javascript (ES6) 中正确定义子类构造函数?
【发布时间】:2017-06-10 17:53:32
【问题描述】:

我在为 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 is not defined in the preloadState 类。为什么会这样?

【问题讨论】:

    标签: javascript class this subclass


    【解决方案1】:

    在子类的构造函数中使用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/

    更深入:

    【讨论】:

    • 太棒了!正是我想要的。后续问题: 1. this.ball 是否可以在 preloadState 中的所有函数中访问? 2. 如何在函数中传递 preloadState 的实例?
    • 好! 1:是的,在preloadState.start() 之后调用的所有方法中。 2:我不明白这个问题。
    • 2.假设我有一个 preloadState 对象:var state = new preloadState()。现在说我想在其他一些功能中使用state.start()function foo(state){ state.start()}。那可能吗?我可以在另一个函数中传递一个类对象吗?
    猜你喜欢
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 2018-11-04
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    相关资源
    最近更新 更多