首頁  >  文章  >  web前端  >  如何在 ES6 中從類別名稱建立物件?

如何在 ES6 中從類別名稱建立物件?

Linda Hamilton
Linda Hamilton原創
2024-11-15 02:59:02267瀏覽

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.

以上是如何在 ES6 中從類別名稱建立物件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn