Ryan King
Ryan King

Reputation: 3696

Javascript creating class object from string

Say I had a class defined within a string like the following:

`class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  
  get area() {
    return this.calcArea();
  }

  calcArea() {
    return this.height * this.width;
  }
}`

Is it possible to turn the string into a javascript class so I could run the following? Or similar..

const square = new Rectangle(10, 10);
console.log(square.area);

Upvotes: 0

Views: 101

Answers (2)

Bmaed Riasbet
Bmaed Riasbet

Reputation: 15028

Looks like a duplicate of this : Using eval method to get class from string in Firefox

Don't forget to put class between parentheses.

var class_str = `(class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }

  get area() {
    return this.calcArea();
  }

  calcArea() {
    return this.height * this.width;
  }
})`;
var a = eval(class_str);
console.log(new a(10, 10));

A working demo here: http://jsbin.com/netipuluki/edit?js,console

Upvotes: 2

Lajos Arpad
Lajos Arpad

Reputation: 76907

You can turn a string into a class if you pass it to eval, like this:

eval("function MyClass(params) {/*Some code*/}");
var foo = new MyClass({a: 1, b: 2});

EDIT:

Based on comments I found out that the syntax shown in the question is ok, but it seems to be incompatible with eval as it is. However, doing some experiments I found the following trick:

eval("window['Rectangle'] = class Rectangle {constructor(height, width) {this.height = height;this.width = width;}get area() {return this.calcArea();}calcArea() {return this.height * this.width;}}");

var r = new Rectangle(50, 40);

Upvotes: 1

Related Questions