javascript: 多个 类 "stored" 在一个对象中?

javascript: multiple classes "stored" within an object?

我觉得我在下面的示例中堆叠多个 classes 的方式存在严重错误: (ps。这个例子只是为了展示我所指的模式)

const itemClasses = {
    ItemOne: class {
            constructor (somethings) {
                        this.thatThing = somethings;
                    }
            doThing() {
                        /*some code*/
                    }
            },
    ItemTwo: class {
            constructor (somethings) {
                        this.thatThing = somethings;
                    }
            doThing() {
                        /*Do another thing!*/
                    }
            }
}

我问这个问题是因为在尝试学习基础知识时我只找到 classes beeing global defined with "class XX()"

的例子

我发现在对象中收集 classes 很整洁,原因有两个。

  1. Keeps 使用许多更小的 classes 时的命名空间清洁器。
  2. 您可以通过编程方式选择不同的 class 更容易:喜欢:
    new entity[variable](param)

是否需要成本资源 (ram/cpu) 将 classes 放入“父对象”中,或者是否有任何其他原因不像这样堆叠 classes。

如果没有问题,再进一步嵌套是不是可以:

 const classes = {
    items = {
        /*Classes in here*/
    },
    entities = {
        /*Classes in here*/
    }
}

ps。我得到了使用 [ES 模块语法] 的重要提示。我还没有理解模块语法主要提供可读性好处,或者如果还有其他实质性收益,请研究它 =D 感谢您到目前为止的回答。

Does it take alot more memory, or is it slower?

不,这是一个非常好的模式。命名空间确实有助于代码组织,尽管它们感觉有点过时 - ES6 模块是必经之路。

Are there any other reason not to do this?

你举的例子

new entity[variable]("xx", "yy")

坏了。这仅在所有 类 具有相同的构造函数签名时才有效,但在您的示例中 ItemOne 需要颜色和大小,而 ItemTwo 需要类型和值。将 "yy" 作为值传递是行不通的,因为 ItemOne 需要一个数字作为大小。

也许这只是因为快速勾勒出示例,但请记住这一点。当然,在某些情况下,即使参数类型不匹配,您仍需要按名称解析 类,但您需要确保参数匹配。