1

I'm a bit confused by how inheritance works for class properties. Here's a representative example:

class Base {
    something = 1;
    constructor() { 
        console.log(this.something);
    }
}

class Child extends Base {
    something = 2;
}

new Child();

this logs 1 to the terminal, where I'd expect it to log 2.

This is just a minimal working example. My actual code is more complicated, but basically my requirements are:

  1. Child should have a property,
  2. that property should be accessible in Base.constructor.
Lachy
  • 218
  • 1
  • 5

1 Answers1

0

I don't think we can directly access child property from parent class. You can pass value after object creation, but it's not an elegant way.

class Base {
    something = null;
    constructor(something) {
        this.something = something;
        alert(this.something);
    }
}

class Child extends Base{
    something = 2;
}

let childObj = new Child();
let baseObj = new Base(childObj.something);

Parent constructor will always be called when you create child object, so I suggest you to use this.something in a separate method instead of constructor.

Ganesh Babu
  • 3,590
  • 11
  • 34
  • 67