首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Javascript:如何在不创建循环依赖的情况下重用创建子实例的方法

Javascript:如何在不创建循环依赖的情况下重用创建子实例的方法
EN

Stack Overflow用户
提问于 2018-09-10 05:20:52
回答 2查看 247关注 0票数 3
代码语言:javascript
运行
复制
abstract class Fruit {
    private content: Fruit[] = [];

    addChild() {
        // Pick one at random (using this as an example instead of the actual criteria that determines this)
        const type = pickOne(['apple', 'banana', 'cherry']);

        switch (type) {
            case 'apple':
                this.content.push(new Apple());
            case 'banana':
                this.content.push(new Banana());
            case 'cherry':
                this.content.push(new Cherry());
        }
    }
}

class Apple extends Fruit { }

class Banana extends Fruit { }

class Cherry extends Fruit { }

我如何在不创建循环依赖关系的情况下重新构造它,以便:

  1. 每个类都在一个单独的文件中
  2. 所有子类都可以使用addChild()方法,而不会复制代码

我读到过基类知道子类的任何信息通常是一个糟糕的模式,但我不确定一个更好的模式会是什么样子。

Example that might make more sense

编辑:删除了type作为参数

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52248742

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档