Tengo la clase Bmw extendida de la clase Car que creé antes, ahora necesito crear un método createNewBmwCar dentro de la class Bmw que creará una nueva instancia de la clase Bmw ...
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(); } }Deberá crear una instancia de Bmw en este método static :
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);El problema no es el método static , es el constructor. Los constructores derivados deben llamar a super() , y deben hacerlo antes de poder usar this .
Si soluciona eso y agrega los parámetros necesarios para createNewBmwCar , funciona (pero siga leyendo):
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" Tiene una segunda opción que puede ser más flexible: puede usar this en lugar de Bmw en el método static , ya que se referirá al constructor en el que llama al método estático:
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" Eso tiene la ventaja de que si crea una subclase de Bmw y luego llama al método static en la subclase, obtendrá una instancia de la subclase, en lugar de un 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