Home >Web Front-end >JS Tutorial >How to Dynamically Instantiate Objects in JavaScript ES6?
Creating objects from class names using old-style syntax in ES6 is causing an error. The following code throws an error:
let className = this.specColumn[name] ? this.specColumn[name] : this.specColumn['__default']; return new window[className](name);
To resolve the issue, remove class names from the specified object and instead use the classes themselves. This eliminates the reliance on global access through the window object. Additionally, the factory can be simplified to an object, as it is typically instantiated only once.
export class Column {} export class Sequence {} export class Checkbox {} export const columnFactory = { specColumn: { __default: Column, // <-- Class reference __sequence: Sequence, // <-- Class reference __checkbox: Checkbox // <-- Class reference }, create(name, ...args) { let cls = this.specColumn[name] || this.specColumn.__default; return new cls(...args); } };
This code stores the classes directly in the specColumn object, allowing for dynamic instantiation of objects using the create method.
The above is the detailed content of How to Dynamically Instantiate Objects in JavaScript ES6?. For more information, please follow other related articles on the PHP Chinese website!