Home > other >  javascript: multiple classes "stored" within an object?
javascript: multiple classes "stored" within an object?

Time:10-15

I have a feeling that there is something terrebly wrong with the way ive stacked multiple classes in the example below: (ps. this example is only to show the pattern im refering to)

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

I ask the question since while trying to learn the basics i only find examples of classes beeing defined globally with "class XX()"

I find it neat to gather classes in objects for two reasons.

  1. Keeps the namespace cleaner when using many smaller classes.
  2. You can programmatically pick different classes easier: Like:
    new entity[variable](param)

Does it take cost resources (ram/cpu) to put classes within "parent objects" or are there any other reason not to stack classes like this.

If there are no issues, would it be fine to go one step further and nest like this:

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

ps. Ive gotten the great tip of using [ES module syntax]. Im yet to understand module syntax gives mostly readability benefits or if there are other substantial gains as well, looking into it =D Thanks for your answers so far.

CodePudding user response:

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

No, it's a totally fine pattern. Namespaces do help with code organisation, although they feel a bit dated - ES6 modules are the way to go.

Are there any other reason not to do this?

The example you gave

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

is broken. This works only if all your classes have the same constructor signature, but in your example ItemOne takes a color and a size whereas ItemTwo takes a type and a value. Passing "yy" as a value doesn't work since ItemOne expects a number as the size.

Maybe that's only because of the quickly sketched example, but keep this in mind. Of course, there are still cases where you need to resolve classes by name even if the parameter types don't match, but you'll need to ensure that the arguments fit.

  • Related