I'm trying to create a ES class definition from a string.
const def = "class M {}";
// ???
const inst = new M();
I'm not in Window, so I can't use DOM based approaches like putting it in script tags. I've tried a few approaches with function()
and eval()
but no real success.
The closest I've come is a pretty ugly factory approach.
const M = new Function('return new class M { test; constructor(){ this.test = "Hello"; } tfun(input){ return input + 7; } }');
const inst = new M();
inst.test; // Hello
inst.tfun(5); // output: 12
This doesn't call the constructor with params though.
const M = new Function('return new class M { test; constructor(param){ this.test = param; } tfun(input){ return input + 7; } }');
const inst = new M("Hello");
inst.test; // undefined