Create object from class name in JavasScript ECMAScript 6

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

    For those of you that are not using ES6 and want to know how you can create classes by using a string here is what I have done to get this to work.

    "use strict";
    
    class Person {
        constructor(x, y) {
            this.x = x;
            this.y = y;
        }
    }
    window.classes = {};
    window.classes.Person = Person;
    
    document.body.innerText = JSON.stringify(new window.classes["Person"](1, 2));
    

    As you can see the easiest way to do this is to add the class to an object.

    Here is the fiddle: https://jsfiddle.net/zxg7dsng/1/

    Here is an example project that uses this approach: https://github.com/pdxjohnny/dist-rts-client-web

提交回复
热议问题