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

Javascript 有没有办法从超类方法内部实例化子类的新实例?,javascript,ecmascript-6,Javascript,Ecmascript 6,我希望能够从超类方法中实例化一个子类的新实例 如果我只有一个没有继承的类,那么很简单: class A { static build(opts) { return new A(opts) } makeAnother() { return A.build(...) } } const a = new A() const a2 = a.makeAnother() 这很有效。但是,它不适用于子类化: class B extend

我希望能够从超类方法中实例化一个子类的新实例

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

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&makeother方法,但我不想重复这些事情。

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

A类{
静态构建(类){
返回新的类()
}   
做另一个(){
返回A.build(this.constructor)
}
}
常数a=新的a()
常数a2=a.makeOther()
console.log(A的a2实例);
类B扩展了{}
常数b=新的b()
const b2=b.makeother()
console.log(B的b2实例)您将要使用

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

除非
build
做的比这里显示的更多,否则您根本不需要它,当然,您宁愿直接
返回新的this.constructor(…)
makeother
makeother

是否希望B的
makeother
返回一个新的
B
对象?如果是这样的话,那么我认为唯一的方法就是重复你自己。是的,返回一个新的B对象——我将在后面澄清为什么当你可以直接调用构造函数时你需要
build()
方法?它不应该是
static build(类,opts)
?如果需要传递一个参数,当然,但它并没有在OP的代码中被传递或使用