Amanda Ferrari
Amanda Ferrari

Reputation: 946

How to instantiate class from static method of abstract class

I would like to know how to instantiate class from static method of abstract class. Something like:

abstract class F {
  static connect() {
    console.log("constructor => ", this.constructor);
    this.constructor();
  }

  constructor() {
    console.log("Hey!");
  }
}

class A extends F {
  constructor() {
    super();
    console.log("hey");
  }
}

Upvotes: 2

Views: 938

Answers (2)

Get Off My Lawn
Get Off My Lawn

Reputation: 36299

When I did something similar, using new this() did not work for me, I resorted to using reflection to create the instance.

The static Reflect.construct() method acts like the new operator, but as a function. It is equivalent to calling new target(...args). It gives also the added option to specify a different prototype.

Source

abstract class F {
  static connect<T extends F>(): T {
    console.log("constructor => ", this.constructor);
    return Reflect.construct(this, []) as T;
  }

  constructor() {
    console.log("Hey!");
  }
}

Next we create an instance of A:

const instanceOfA = A.connect();

Upvotes: 4

SourceOverflow
SourceOverflow

Reputation: 2048

You could do it, but you probably shouldn't.

This idea seems like a big code smell to me.

What are you trying to achieve by it? In the best case scenario you're replacing new A() with A.connect(). This just obfuscates what is happening and doesn't actually add anything.

I sadly can't tell you what the better approach would be without knowing more context, but I'd recommend re-thinking your design choices that led to this.

(And I do mean no offence by this. I've myself done pretty hacky bad code and JS and to a lesser degree TS allow for this. This was just meant as a friendly recommendation)

How you could do it (for science)

class F {
  static connect() {
    return new this()
  }
}

If F is abstract, you could still do it using return new (this as any)() since javascript actually doesn't have abstract classes built-in.

Derived classes of F e.g. A.connect() will then create instances of A.

However, this basically goes against both how static methods and Typescript are meant to be used

Upvotes: -1

Related Questions