iansmathew
iansmathew

Reputation: 387

How to properly define subclass constructors in Javascript (ES6)?

I have trouble making a constructor for subclasses in JS. The constructors for classes work fine though!

//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();

}

When running the code, I get the error this.ball is not defined in the preloadState class. Why is that so?

Upvotes: 4

Views: 3483

Answers (1)

Pimmol
Pimmol

Reputation: 1871

Before you can use this in a subclass' constructor, you have to call super:

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

Example: https://jsfiddle.net/n0ek40ph/

Another option is not to override the constructor:

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

Example: https://jsfiddle.net/n0ek40ph/3/

More in depth:

Upvotes: 4

Related Questions