React/Javascript - Conceptual approach for executing Javascript Code from string

Viewed 207

currently i am having a conceptional issue in my application.

A user should be able to create a Javascript class inside my react/redux application and my application should be able to execute the written javascript code.

Example, User A writes:

class PredefinedClassName {
  constructor(a) {
    this.a = a;
  }

  getSomething(parameterFromOutside) {
    return this.a * parameterFromOutside;
  }
}

This class is then saved as a string(important) in some database.

Next i want to load this class(as a string again) and do the following:

  1. Create instance of this class which is contained in the string... (How?)
  2. Call "getSomething" method on the instance and pass my own parameter to the method(How?)

As this is a quite rare use case, there is only very few literature about and almost no library.

Site note: On top of it, i should also check for syntax and runtime errors, but i consider this as the next step so first i would like to solve the elementary part.

Do you have any ideas about how solve this conceptional issue?

Thanks and Greetings!

1 Answers

Creating an instance of the class which is stored in a string is quite easy actually, browsers basically do that in the background. All you need to do is the following:

// Save your javascript class in a string variable:
const classString = `class PredefinedClassName {
  constructor(a) {
    this.a = a;
  }

  getSomething(parameterFromOutside) {
    return this.a * parameterFromOutside;
  }
}`;

// Create an instance of this class with eval() function, by appending the original class declaration before the instantiation, and do not return the newly created class inside the eval, just create it like so:
const customParameterValue = 5;
const instanceOfClass = eval(classString + `new PredefinedClassName(${customParameterValue})`)

// Now you can use 'instanceOfClass' as usual:
instanceOfClass.getSomething(10)

Feel free to ask for any clarification in the comments:)

Related