0

Wonder if anyone can help?

I'm trying to call a parent's constructor or at a minimum get a reference to the parent class in some way without hardcoding anything.

class A {
  static foo(options) {
    parent::__construct(options); <- this is how you would get the parent in php
  }
}

class B extends A {

}


Is this possible?

Jammer
  • 1,548
  • 20
  • 37
  • 3
    [`super`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super) – Pointy Mar 11 '20 at 13:48
  • Does this answer your question? [Inheritance and Super in JavaScript](https://stackoverflow.com/questions/41180655/inheritance-and-super-in-javascript) – JDB Mar 11 '20 at 13:50

2 Answers2

1

In a javascript class (and OOP in general), a static method is not part of an instance and therefore the object it resides in does not have a constructor.

You should avoid using static method for this sort of thing and use a standard constructor and call super() to call the parent constructor.

class A {
  constructor(options) {
    console.log('Options are:');
    console.log(options);
  }
}

class B extends A {
    constructor(options) {
       super(options);
    }
}

const item = new B({item1: 'abc'});

Further reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super

Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133
0

You can use super() to call parent constructor

class A {
  constructor() {
    console.log('I\'m parent ');
  }
  
  foo(){
     console.log('Class A: Called foo');
  }
  
}


class B extends A {
  constructor() {
    super();
  }
  
  foo(){
     super.foo()
  }
}


const b = new B();
b.foo();
Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35