在 JavaScript ECMAScript 6 中从类名创建对象 [英] Create object from class name in JavasScript ECMAScript 6

查看:25
本文介绍了在 JavaScript ECMAScript 6 中从类名创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 ES6 创建对象工厂,但旧式语法不适用于新式.

I want create object factory using ES6 but old-style syntax doesn't work with new.

我有下一个代码:

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

我做错了什么?

推荐答案

不要把类名放在那个对象上.将类本身放在那里,这样您就不必依赖它们是全局的并且可以通过 window 访问(在浏览器中).

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

顺便说一句,没有充分的理由让这个工厂成为一个类,你可能只会实例化一次(单例).把它变成一个对象:

Btw, there's no good reason to make this factory a class, you would probably only instantiate it once (singleton). Just make it an object:

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

这篇关于在 JavaScript ECMAScript 6 中从类名创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆