简体   繁体   中英

How to implement abstract factory in js?

I want to implement very simple abstract factory pattern but I am facing this error. Also am I doing something wrong with my code? How can I improve this to make it work properly?

Must call super constructor in derived class before accessing 'this' or returning from derived constructor"

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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