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

How to Dynamically Instantiate Objects in JavaScript ES6?

Linda Hamilton
Release: 2024-12-05 11:18:14
Original
992 people have browsed it

How to Dynamically Instantiate Objects in JavaScript ES6?

Dynamic Object Instantiation in JavaScript ES6

Problem Statement

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

Solution

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.

Code Fix

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

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!

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