Search code examples
javascriptjsonecmascript-6es6-classes6-proxy

javascript create dynamic class by object


Task: I want to create a dynamic class by a given JSON Object in ES6.

After a lot of reading in the MDN web docs and much stackoverflow questions i'm totally confused how to get this work.

JSON Object

{
    constructor: {
        name: "someName",
    },
    getter: {
        function1: () => "someOutput",
        function2: () => false,
    }
}

While I tried to solve the problem I figured out how to create dynamic getter methods by using "Proxy" or "defineProperty" but how i should handle the constructor?? :(

I hope someone can help me with a hint or an example. Thanks in advance


Solution

  • You can add constructor to your class created by Proxy using Proxy's "construct" handler method:

    const jsonObj = {
        constructor: {
            name: "someName",
        },
        getter: {
            function1: () => "someOutput",
            function2: () => false,
        }
    }
    
    
    function baseClass(obj) {
      for(i in obj){
        this[i] = obj[i]
    
      }
    }
    
    const handler = {
      construct(target, args) {
        return new target(jsonObj.constructor);
      }
    };
    
    const NewClass = new Proxy(baseClass, handler);