Home > Web Front-end > JS Tutorial > How to Create an Object from a Class Name in JavaScript Using ES6?

How to Create an Object from a Class Name in JavaScript Using ES6?

Barbara Streisand
Release: 2024-11-23 09:53:31
Original
645 people have browsed it

How to Create an Object from a Class Name in JavaScript Using ES6?

Create Object from Class Name in JavaScript ECMAScript 6

Q: I'm trying to create an object factory using ES6, but the old-style syntax doesn't work with the new one. I have the following code:

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 throws an error
    }
}

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

What am I doing wrong?

A: You don't have to put class names on the object. Instead, put the classes themselves there so that you don't have to rely on them being global and accessible (in browsers) through the window object.

Additionally, there's no reason to make the factory a class since you would probably only instantiate it once (singleton). You can make it an object instead:

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

The above is the detailed content of How to Create an Object from a Class Name in JavaScript Using 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