Create object from class name in JavasScript ECMAScript 6

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

    There is a small & dirty way to do that:

    function createClassByName(name,...a) {
        var c = eval(name);
        return new c(...a);
    }
    

    You can now create a class like that:

    let c = createClassByName( 'Person', x, y );
    

提交回复
热议问题