Home > Web Front-end > JS Tutorial > body text

How to Create Objects from Class Names in JavaScript ES6?

Susan Sarandon
Release: 2024-11-11 18:17:03
Original
761 people have browsed it

How to Create Objects from Class Names in JavaScript ES6?

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

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

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!

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