简体   繁体   English

如何在js中实现抽象工厂?

[英]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"在访问“this”或从派生构造函数返回之前,必须在派生类中调用超级构造函数”

You need to call super() inside constructor:您需要在构造函数中调用super()

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: ES2015(ES6)类的规则基本上可以归结为:

  • In a child class constructor, this cannot be used until super is called.在子类构造函数中,在调用 super 之前不能使用 this。
  • 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. ES6 类的构造函数必须调用 super 如果它们是子类,或者它们必须显式返回一些对象来代替未初始化的对象。

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)

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

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