OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Create Class Definition from String

  • Thread starter Thread starter Randy Buchholz
  • Start date Start date
R

Randy Buchholz

Guest
I'm trying to create a ES class definition from a string.

Code:
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.

Code:
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.

Code:
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

<p>I'm trying to create a ES class definition from a string.</p>
<pre><code>const def = "class M {}";
// ???
const inst = new M();
</code></pre>
<p>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 <code>function()</code> and <code>eval()</code> but no real success.</p>
<p>The closest I've come is a pretty ugly factory approach.</p>
<pre><code>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
</code></pre>
<p>This doesn't call the constructor with params though.</p>
<pre><code>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
</code></pre>
 

Latest posts

Online statistics

Members online
0
Guests online
2
Total visitors
2
Top