Create object from class name in JavasScript ECMAScript 6

前端 未结 6 1683
感动是毒
感动是毒 2020-11-22 15:46

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 {}         


        
6条回答
  •  面向向阳花
    2020-11-22 16:04

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

提交回复
热议问题