簡體   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