Creating Objects from Class Names in JavaScript ES6
When attempting to create objects from class names using standard ES6 syntax, you may encounter errors. The following code demonstrates this:
import "./myModule.js"; class Column {} class Sequence {} class Checkbox {} 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');
The error arises because the class names are not globally accessible or available through the window object.
Solution:
To address this issue, the classes themselves should be stored in the factory object instead of their names. This approach eliminates the need to rely on global accessibility and simplifies the factory implementation.
import "./myModule.js"; class Column {} class Sequence {} class Checkbox {} 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 Objects from Class Names in JavaScript ES6?. For more information, please follow other related articles on the PHP Chinese website!