1

Lets assume i have a baseclass and i want to inherit the properties from the constructor.


Note: This is an example code. It is not intended to work or anything, just to demonstrate my problem

Base Class

class BaseClass {
    constructor(a, b) {
        this.a = a;
        this.b = b;
    }
    
    /* SOME CLASS METHODS */ }

Myclass

class Myclass extends BaseClass {
    constructor() {
        super();
    };

/* SOME CLASS METHODS */ }

MyProblem

let test = Myclass('dog', 'cat');

However, this doesnt seem to work. Why does the Myclass-constructor not initialize the BaseClass constructor? When i look at the debugger for this.a and this.b, this values are undefined.

2 Answers 2

3

you need to pass through an a and b value to the super method

like here:

class Myclass extends BaseClass {
    constructor(a, b) {
        super(a, b);
};

super

Sign up to request clarification or add additional context in comments.

Comments

2
constructor() {
    super();
};

Your child class is overriding the constructor, is not accepting any arguments, and passes no arguments to the parent constructor (super()), so all parameters in the parent constructor are undefined. Your child constructor needs to accept the same or more parameters, and/or provide default arguments to super().

In this particular case, the child constructor doesn't do anything, so may as well be omitted entirely.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.