Create object from class name in JavasScript ECMAScript 6

Don’t put class names on that object. Put the classes themselves there, so that you don’t have to rely on them being global and accessible (in browsers) through window.

Btw, there’s no good reason to make this factory a class, you would probably only instantiate it once (singleton). Just make it an object:

export class Column {}
export class Sequence {}
export class Checkbox {}

export const columnFactory = {
    specColumn: {
        __default: Column,    // <--
        __sequence: Sequence, // <--
        __checkbox: Checkbox  // <--
    },
    create(name, ...args) {
        let cls = this.specColumn[name] || this.specColumn.__default;
        return new cls(...args);
    }
};

Leave a Comment