繁体   English   中英

有没有办法从超类方法内部实例化子类的新实例?

[英]Is there a way to instantiate a new instance of a subclass from inside a super class method?

我希望能够从超类方法内部实例化子类的新实例。

如果我只有一个没有继承的类,那就很简单了:

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

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

这有效。 但是,它不适用于子类化:

class B extends A { ... }

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

我想我可以将 build 和 makeAnother 方法添加到每个子类中,但我不想重复。

您可以在超类中引用this.constructor以获取子类的构造函数(或超类本身,如果该方法是在超实例而不是子实例上调用的):

 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);

你会想要使用

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

除非build做的比这里显示的多,你当然根本不需要它,你宁愿直接在makeAnother return new this.constructor(...)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM