Home > Web Front-end > JS Tutorial > How to Create Objects Dynamically in JavaScript ES6 Using Class Objects?

How to Create Objects Dynamically in JavaScript ES6 Using Class Objects?

Barbara Streisand
Release: 2024-11-15 19:25:02
Original
201 people have browsed it

How to Create Objects Dynamically in JavaScript ES6 Using Class Objects?

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);
    }
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template