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

How to Create Objects from Class Names in ES6?

Linda Hamilton
Linda HamiltonOriginal
2024-11-15 02:59:02266browse

How to Create Objects from Class Names in ES6?

Creating Objects from Class Names in JavaScript ES6

When attempting to create an object factory in ES6 using the traditional old-style syntax, you may encounter an error. This is because the old syntax is incompatible with the new ES6 syntax.

In the provided code snippet:

export class Column {}
export class Sequence {}
export class Checkbox {}

export 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 throw error
    }
}

let factory = new ColumnFactory();
let column = factory.create('userName');

The error occurs in the line return new window[className](name); because it attempts to access the class name as a global variable. This approach fails in ES6, as classes are not exposed as global variables.

Solution:

To resolve this issue, replace the class names in the specColumn object with the actual class references:

export class Column {}
export class Sequence {}
export class Checkbox {}

export const columnFactory = {
    specColumn: {
        __default: Column,    // <--
        __sequence: Sequence, // <--
        __checkbox: Checkbox  // <--
    },
    create(name, ...args) {
        let cls = this.specColumn[name] || this.specColumn.__default;
        return new cls(...args);
    }
};

By doing so, you no longer rely on class names being available globally and can access classes directly from the specColumn object.

The above is the detailed content of How to Create Objects from Class Names in 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