且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在JavasScript ECMAScript 6中从字符串创建对象

更新时间:2023-11-08 07:49:51

不要在该对象上放置类名。将课程自己放在那里,以便您不必依靠他们在全球和可访问(在浏览器中)通过窗口


$ btw,没有什么好的理由让这个工厂成为一个类,你可能只会实例化一次(单例)。只需使它成为一个对象:
  export class Column {} 
export class Sequence {}
export class复选框{}

export const columnFactory = {
specColumn:{
__default:Column,//< -
__sequence:Sequence,//< -
__checkbox:复选框//< -
},
create(name,... args){
let cls = this.specColumn [name] || this.specColumn .__默认;
返回新的cls(... args);
}
};


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

I have next 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 throw error
    }
}

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

What do I do wrong?

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