Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 485
Serhii Popov Avatar asked Aug 02 '15 21:08

Serhii Popov


2 Answers

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);
    }
};
like image 76
Bergi Avatar answered Sep 22 '22 08:09

Bergi


There is a small & dirty way to do that:

function createClassByName(name,...a) {
    var c = eval(name);
    return new c(...a);
}

You can now create a class like that:

let c = createClassByName( 'Person', x, y );
like image 34
eco747 Avatar answered Sep 20 '22 08:09

eco747