2

I would like to be able to instantiate a new instance of a subclass from inside a superclass method.

If I have just a single class with no inheritance, it is straight forward:

class A {
    static build(opts) {
        return new A(opts)
    }   
    makeAnother() {
        return A.build(...)
    }
}

const a = new A()
const a2 = a.makeAnother()

This works. However, it doesn't work with subclassing:

class B extends A { ... }

const b = new B()
const b2 = b.makeAnother() // this returns an instance of A, not B

I suppose I could add the build & makeAnother methods to each subclass, but I would rather not repeat things.

react_or_angluar
  • 1,568
  • 2
  • 13
  • 20
user1031947
  • 6,294
  • 16
  • 55
  • 88

2 Answers2

1

You can reference this.constructor inside the super class to get to the constructor of the subclass (or the super class itself, if the method is called on a super instance rather than a sub instance):

class A {
    static build(theClass) {
        return new theClass()
    }   
    makeAnother() {
        return A.build(this.constructor)
    }
}

const a = new A()
const a2 = a.makeAnother()
console.log(a2 instanceof A);

class B extends A { }

const b = new B()
const b2 = b.makeAnother()
console.log(b2 instanceof B);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

You'll want to use

class A {
    static build(opts) {
        return new this(opts)
    }   
    makeAnother() {
        return this.constructor.build(...)
    }
}

Unless build does more than shown here, you don't need it at all of course, you'd rather directly return new this.constructor(...) in makeAnother.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375