0

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);

2
  • have you tried JSON.parse()? Commented Aug 17, 2017 at 10:35
  • You can do exactly what you want if you just omit the quotation marks. Commented Aug 17, 2017 at 10:36

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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);

8 Comments

It is valid syntax - see prototype methods section developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes
Great, but I doesn't look like that works with class declarations. Might be able to work around with functions though...
The syntax is perfectly fine
@DarrenSweeney indeed, I was wrong from that point of view, I have edited the answer.
@RyanKing yes, it just evaluated it and later it could not be used. However, I found a trick, which is a methodology you could achieve what you want with minimal changes.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.