SagiSergioNadir SagiSergioNadir - 1 year ago 79
Javascript Question

es6 get access to class constructor from static function

I am trying to create a static function that generated a new instance. The instance is of the class the static function belongs to.

Here's an example

class A {
static getInstance() {
return new A();

So far so good
let a = A.getInstance();
will work fine.

I want to inherit this functionality in children classes.

class B extends A {}
let b = B.getInstance(); // This will return an instance of A.

I want
to return an instance of B.

Answer Source

This seems to work.. I assume you want this as you want to pass a class as some sort of constructor / generator. As doing new A() is obviously a bit simpler.

class A {
  sayIt() { console.log('I am A'); }
  static getInstance() {
    return new this;

class B extends A { sayIt() { console.log('I am B') } }

var k = A.getInstance();

let b = B.getInstance(); 

let k2 = new A();

let b2 = new B();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download