Q: I'm trying to create an object factory using ES6, but the old-style syntax doesn't work with the new one. I have the following 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 throws an error } } let factory = new ColumnFactory(); let column = factory.create('userName');
What am I doing wrong?
A: You don't have to put class names on the object. Instead, put the classes themselves there so that you don't have to rely on them being global and accessible (in browsers) through the window object.
Additionally, there's no reason to make the factory a class since you would probably only instantiate it once (singleton). You can make it an object instead:
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); } };
The above is the detailed content of How to Create an Object from a Class Name in JavaScript Using ES6?. For more information, please follow other related articles on the PHP Chinese website!