SagiSergioNadir SagiSergioNadir - 17 days ago 8
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
B.getInstance()
to return an instance of B.

Answer

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();
k.sayIt();

let b = B.getInstance(); 
b.sayIt();

let k2 = new A();
k2.sayIt();

let b2 = new B();
b2.sayIt();