Getting variables from already defined class with inheritance

So, say I have class B that inherits class A like so:

class A {
    constructor(varA) {
         var varA = this.varA;
    }
}

class B extends A {
    constructor() {
        console.log(varA);
    }
}

What would I have to do to make it so that a new class B can inherit the varA defined in a new class A?

You have to call the parent constructor first:

class B extends A {
    constructor() {
        super();
        console.log(varA);
    }
}
1 Like

Yes. This is a correct answer. using super() will solve the issue.

@rpkamp @satyendra2 The problem is is that it then calls class A more than once, which screws things up.

You shouldn’t call the constructor more than once anyway :slight_smile:

It does not; and if you call super() more than once it will actually throw an error.

You got it the wrong way round here: you have to assign this.varA = varA so that’s available to subclasses and other methods. And any subclass will have to actually pass that argument to the parent constructor, e.g. by just forwarding its own constructor arguments like

class A {
  constructor (varA) {
    this.varA = varA
  }
}

class B extends A {
  constructor (...args) {
    super(...args)
    console.log(this.varA)
  }
}

const b = new B('foo') // logs "foo"

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.