Search code examples
javascriptecmascript-6es6-class

Create object from class name in JavasScript ECMAScript 6


I want create object factory using ES6 but old-style syntax doesn't work with new.

I have next code:

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

export class ColumnFactory {
    constructor() {
        this.specColumn = {
            __default: 'Column',
            __sequence: 'Sequence',
            __checkbox: 'Checkbox'
        };
    }

    create(name) {
        let className = this.specColumn[name] ? this.specColumn[name] : this.specColumn['__default'];
        return new window[className](name); // this line throw error
    }
}

let factory = new ColumnFactory();
let column = factory.create('userName');

What do I do wrong?


Solution

  • 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);
        }
    };