Search code examples
javascriptreactjsreduxsandboxenvironment

Conceptual approach for executing Javascript code from string


Currently, I am having a conceptual issue with 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.

For 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 an 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 little literature about it and almost no libraries.

Side 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 to solve this conceptual issue?


Solution

  • 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:)