Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Class Definition from String

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 
like image 412
Randy Buchholz Avatar asked Nov 01 '25 06:11

Randy Buchholz


1 Answers

One way to achieve this is to add the text that instantiates the class to the string and only then eval it:

const def = 'class M {}';
const instantiator = def + '; new M();';

const m = eval(instantiator);

EDIT:
To follow-up on the comment, if you want the class itself, it's even simpler - just add its name to the string you're evaluating:

const def = 'class M {}';
const statement = def + '; M;';

const M = eval(statement);
const m = new M(); // This now works!
like image 137
Mureinik Avatar answered Nov 02 '25 20:11

Mureinik