Create object from class name in JavasScript ECMAScript 6

前端 未结 6 1607
感动是毒
感动是毒 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:23

    The problem is that the classes are not properties of the window object. You can have an object with properties "pointing" to your classes instead:

    class Column {}
    class Sequence {}
    class Checkbox {}
    let classes = {
      Column,
      Sequence,
      Checkbox 
    }
    
    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 classes[className](name); // this line no longer throw error
        }
    }
    
    let factory = new ColumnFactory();
    let column = factory.create('userName');
    
    export {ColumnFactory, Column, Sequence, Checkbox};
    

提交回复
热议问题