1

I have a abstract base class that controls a lot of the heavy lifting for subclasses, and I want to add a static factory method to insatiate the object that would work in a similar way to PHP's static keyword.

I am currently calling the abstract classes static method and passing it a constructor of a subclass type: Subclass.fromFile({}, Subclass), which is so elegant.

Current Implementation

class AbstractClass {
    //...

    static fromFile(attributes, constructor) {
        return new constructor(attributes)
    }

    //...
}

Is there a JS equivalent to PHP's new static()?

Dov Benyomin Sohacheski
  • 7,133
  • 7
  • 38
  • 64

1 Answers1

2

The answer is almost trivial. Apparently JS passes this to static methods as the caller's class instance.

You can therefore instantiate the object using new this(args) from within the static method.

Example

abstract class AbstractClass {
    static fromFile(attributes) {
        console.log(this) // [LOG] class A {}
        return new this(attributes)
    }
}

class A extends AbstractClass {}

console.log(A.fromFile([])) // [LOG] A
Dov Benyomin Sohacheski
  • 7,133
  • 7
  • 38
  • 64