Creating Objects Dynamically in JavaScript ES6
Difficulty in constructing objects from class names using ES6 can be encountered when adopting a traditional approach. This article aims to resolve this issue and provide an effective method to create objects dynamically using ES6 syntax.
The previous code snippet attempts to utilize a factory to create objects based on their class names. However, an error is encountered due to referencing classes through the global object 'window'.
To address this, it is recommended to store the class objects themselves rather than their names in the factory's 'specColumn' object. This ensures that the classes are accessible without relying on them being globally available.
Additionally, converting the factory into an object instead of a class may be more appropriate given its singleton-like usage scenario. Here's the updated code:
export class Column {} export class Sequence {} export class Checkbox {} export const columnFactory = { specColumn: { __default: Column, // <-- Class object __sequence: Sequence, // <-- Class object __checkbox: Checkbox // <-- Class object }, create(name, ...args) { let cls = this.specColumn[name] || this.specColumn.__default; return new cls(...args); } };
By implementing these modifications, it becomes possible to create objects dynamically using ES6 syntax.
The above is the detailed content of How to Create Objects Dynamically in JavaScript ES6 Using Class Objects?. For more information, please follow other related articles on the PHP Chinese website!