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?

2

2 Answers 2

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

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

Comments

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

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.