Create object from class name in JavasScript ECMAScript 6

前端 未结 6 1654
感动是毒
感动是毒 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条回答
  •  旧时难觅i
    2020-11-22 16:21

    I know this is an old post, but recently I've had the same question about how to instance a class dynamically

    I'm using webpack so following the documentation there is a way to load a module dynamically using the import() function

    js/classes/MyClass.js

    class MyClass {
        test = null;
        constructor(param) {
            console.log(param)
            this.test = param;
        }
    }
    

    js/app.js

    var p = "example";
    var className = "MyClass";
    
    import('./classes/'+className).then(function(mod) {
        let myClass = new mod[className](p);
        console.log(myClass);
    }, function(failMsg) {
        console.error("Fail to load class"+className);
        console.error(failMsg);
    });
    

    Beware: this method is asynchronous and I can't really tell the performance cost for it, But it works perfectly on my simple program (worth a try ^^)

    Ps: To be fare I'm new to Es6 (a couple of days) I'm more a C++ / PHP / Java developer.

    I hope this helps anyone that come across this question and that is it not a bad practice ^^".

提交回复
热议问题