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
Post a Comment