当前我的申请中有概念性问题。
用户应该能够在我的react / redux应用程序中创建一个Javascript类,并且我的应用程序应该能够执行编写的javascript代码。
示例,用户A写道:
class PredefinedClassName {
constructor(a) {
this.a = a;
}
getSomething(parameterFromOutside) {
return this.a * parameterFromOutside;
}
}
然后将该类另存为字符串(重要)在某些数据库中。
接下来,我想加载该类(再次作为字符串)并执行以下操作:
因为这是一个非常罕见的用例,所以关于它的文献很少,几乎没有库。
站点注释:最重要的是,我还应该检查语法和运行时错误,但是我认为这是下一步,因此首先我想解决基本部分。
您对如何解决此概念性问题有任何想法吗?
感谢和问候!
实际上,创建存储在字符串中的类的实例非常容易,浏览器基本上是在后台执行此操作。您需要做的是以下操作:
// 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)
随时要求在评论中进行任何澄清:)