javascript - Create object from string in JavasScript ECMAScript 6 -


i want create object factory using es6 old-style syntax doesn't work 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); // line throw error     } }  let factory = new columnfactory(); let column = factory.create('username'); 

what do wrong?

don't put class names on object. put classes there, don't have rely on them being global , accessible (in browsers) through window.

btw, there's no reason make factory class, instantiate once (singleton). make 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);     } }; 

Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -