Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/461.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Javascript(ES6)中正确定义子类构造函数?_Javascript_Class_This_Subclass - Fatal编程技术网

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

如何在Javascript(ES6)中正确定义子类构造函数?,javascript,class,this,subclass,Javascript,Class,This,Subclass,我在为JS中的子类创建构造函数时遇到困难。类的构造函数工作得很好 //defining base class State class State { constructor(){ this.someText = "someText"; } start(){ } update(){ } exit(){ } } //defining subclass preloadState class preload

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

在子类的构造函数中使用
this
之前,必须调用
super

class preloadState extends State {
    constructor() {
        super();
        this.ball = "red";
    }
}
例如:

另一个选项是不重写构造函数:

class preloadState extends State {
    start() {
        this.ball = "red";
        console.log(this.ball);
    }
}
例如:

更深入:


太好了!正是我想要的。跟进问题:1。此.ball是否可在预加载状态下访问所有函数?2.如何在函数中传递preloadState实例?很好!1:是的,在
preload state.start()
之后调用的所有方法中。他说:我不明白这个问题。假设我有一个prelostate对象:
var state=new prelostate()
。现在假设我想在其他函数中使用
state.start()
<代码>函数foo(state){state.start()}。那可能吗?我可以在另一个函数中传递类对象吗?