繁体   English   中英

如何创建一个从 class 创建新实例的方法?

[英]how to create a method which creates new instance from class?

I have Bmw class extended from Car class I created before, now I need to create a createNewBmwCar method inside Bmw class which will create new instance from Bmw class...

 class Bmw extends Car { constructor(options) { this._model = options.model; this._year = options.year; this._price = options.price; } static createNewBmwCar() { // return FIXME: let newCar = new Bmw(); } }

您将需要在此static方法中实例化Bmw

 class Car {}; class Bmw extends Car { constructor(options) { super(options); this._model = options.model; this._year = options.year; this._price = options.price; } static createNewBmwCar(options) { return new Bmw({ model: "BMW", year: options.year, price: options.price }); } } let myBMW = Bmw.createNewBmwCar({ year: 2020, price: "1$" }); console.log(myBMW);

问题不在于static方法,而是构造函数。 派生的构造函数必须调用super() ,并且必须这样做才能使用this

如果您解决了这个问题,并将必要的参数添加到createNewBmwCar ,它就可以工作(但请继续阅读):

 class Car { } class Bmw extends Car { constructor(options) { super(); // <========= this._model = options.model; this._year = options.year; this._price = options.price; } static createNewBmwCar(options) { let newCar = new Bmw(options); return newCar; } } const beemer = Bmw.createNewBmwCar({ model: "fancy", year: "recent", price: "lots", }); console.log(beemer._model); // "fancy"

您确实有第二个选项可能更灵活:您可以在static方法中使用this而不是Bmw ,因为它将引用您调用 static 方法的构造函数:

static createNewBmwCar(options) {
    let newCar = new this(options);
    //               ^^^^
    return newCar;
}

 class Car { } class Bmw extends Car { constructor(options) { super(); // <========= this._model = options.model; this._year = options.year; this._price = options.price; } static createNewBmwCar(options) { let newCar = new Bmw(options); return newCar; } } const beemer = Bmw.createNewBmwCar({ model: "fancy", year: "recent", price: "lots", }); console.log(beemer._model); // "fancy"

这样做的好处是,如果您创建Bmw的子类,然后在子类上调用static方法,您将获得子类的实例,而不是Bmw

 class Car { } class Bmw extends Car { constructor(options) { super(); // <========= this._model = options.model; this._year = options.year; this._price = options.price; } static createNewBmwCar(options) { let newCar = new this(options); return newCar; } } class BmwSpecial extends Bmw { } const beemer = BmwSpecial.createNewBmwCar({ model: "fancy", year: "recent", price: "lots", }); console.log(beemer instanceof BmwSpecial); // true, would be false with the earlier version

暂无
暂无

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

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