Home  >  Article  >  Web Front-end  >  How to Create Objects from Class Names in JavaScript ES6?

How to Create Objects from Class Names in JavaScript ES6?

Susan Sarandon
Susan SarandonOriginal
2024-11-11 18:17:03762browse

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');

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);
    }
};

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!

Statement:
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