如何从React Native中的字符串运行javascript逻辑?
在我的应用程序中,第三方游戏开发人员将基于我的模板编写简单的javascript逻辑。他们会在网上的文本框中输入他们的代码,我会将他们的代码存储为字符串 例如,一个游戏开发者会这样写:如何从React Native中的字符串运行javascript逻辑?,javascript,react-native,compilation,interpreter,Javascript,React Native,Compilation,Interpreter,在我的应用程序中,第三方游戏开发人员将基于我的模板编写简单的javascript逻辑。他们会在网上的文本框中输入他们的代码,我会将他们的代码存储为字符串 例如,一个游戏开发者会这样写: const examineItem = (user, item, app) => { //we will pass `user` and `item` with our own methods //Developer writes his/her own logic if(user.inte
const examineItem = (user, item, app) => { //we will pass `user` and `item` with our own methods
//Developer writes his/her own logic
if(user.intelligence > 50){
return({ result: "You see a rock!"});
}else{
return({ result: "You see nothing"});
}
};
在我的React原生应用程序中,如何将此字符串代码转换为可运行函数?我需要翻译吗?我是否使用已弃用的eval
从哪里开始?其实并不难。使用新的函数运算符,如下所示:
const examineItem = (user, item, app) => {
// Developer writes his/her own logic
const devString = 'return user.intelligence > 50'
// You can pass as many arguments as you want, just keep the string last:
const devFunc = new Function('user', 'item', 'app', devString)
// Make sure to pass all the arguments to the call:
if(devFunc(user, item, app)){
return({ result: "You see a rock!"});
} else{
return({ result: "You see nothing"});
}
};
// Testing it:
const user = { intelligence: 60 }
const res = examineItem(user, null, null)
console.log(res) // { result: "You see a rock!"}
我刚刚测试了这段代码,它应该可以工作。你可以把devString从任何你想要的地方拉出来
这样做的主要危险在于确保所有开发人员都知道哪些参数将传递给他们编写的字符串,以及这些参数的数据模型。这其实并不难。使用新的函数运算符,如下所示:
const examineItem = (user, item, app) => {
// Developer writes his/her own logic
const devString = 'return user.intelligence > 50'
// You can pass as many arguments as you want, just keep the string last:
const devFunc = new Function('user', 'item', 'app', devString)
// Make sure to pass all the arguments to the call:
if(devFunc(user, item, app)){
return({ result: "You see a rock!"});
} else{
return({ result: "You see nothing"});
}
};
// Testing it:
const user = { intelligence: 60 }
const res = examineItem(user, null, null)
console.log(res) // { result: "You see a rock!"}
我刚刚测试了这段代码,它应该可以工作。你可以把devString从任何你想要的地方拉出来
这样做的主要危险在于确保所有开发人员都知道哪些参数将传递给他们编写的字符串,以及这些参数的数据模型,不要忘记,如果没有正确封装,自定义用户代码可能会改变变量。我强烈建议您阅读IIFEs函数
例如,user.intelligence=1000;//将更改所有用户对象我曾经做过一个类似的项目,不要忘记,如果没有正确封装,自定义用户代码可以更改变量。我强烈建议您阅读IIFEs函数
例如,user.intelligence=1000;//将更改所有用户对象谢谢。如果我想让开发人员编写一个包含属性的完整类,该怎么办?你的建议是什么?它的需求/用例是什么?如果只在本地使用,则可以在新函数调用中创建类。谢谢。如果我想让开发人员编写一个包含属性的完整类,该怎么办?你的建议是什么?它的需求/用例是什么?如果只在本地使用,那么可以在新函数调用中创建一个类。很好!在传递到ExamineItemPoint之后复制变量并不是一个坏主意!将变量传递给testeitem后制作副本不是一个坏主意