You need to call super()
inside constructor:
class MakeMeatPizza extends MakePizza {
constructor() {
super();
super.createPizza("meat");
}
}
So thanks to this beautiful answer:
The rules for ES2015 (ES6) classes basically come down to:
- In a child class constructor, this cannot be used until super is called.
- ES6 class constructors MUST call super if they are subclasses, or they must explicitly return some object to take the place of the one
that was not initialized.
And the code looks like this:
class Pizza {
constructor(name,size,type) {
this.name = name;
this.size = size;
this.type = type;
}
prepare() {
console.log("prepare");
}
bake() {
console.log("bake");
}
deliver() {
console.log("deliver");
}
}
class MeatPizza extends Pizza {
constructor() {
super("Chicago style pizza", "Large", "Meat")
}
}
class VegePizza extends Pizza {
constructor() {
super("Only natural", "Large", "Vegetarian")
}
}
class MakePizza {
createPizza(type) {
switch (type) {
case "meat":
return new MeatPizza()
case "vege":
return new VegePizza()
default:
throw new Error("Something went wrong...");
}
}
}
class MakeMeatPizza extends MakePizza {
constructor() {
super()
}
create() {
return this.createPizza("meat")
}
}
class MakeVegePizza extends MakePizza {
constructor() {
super()
}
create() {
return this.createPizza("vege")
}
}
class OrderPizza {
}
const test = new MakeVegePizza().create();
console.log(test)