TIM*_*MEX 1 javascript interpreter compilation react-native
在我的应用程序中,第三方游戏开发人员将根据我的模板编写简单的 JavaScript 逻辑。他们将把他们的代码输入到文本框(在线),我将他们的代码存储为字符串。
例如,一位游戏开发者会这样写:
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"});
}
};
Run Code Online (Sandbox Code Playgroud)
在我的 React Native 应用程序中,如何将此字符串代码“转换”为可运行的函数?我需要翻译吗?我是否使用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!"}
Run Code Online (Sandbox Code Playgroud)
我刚刚测试了这段代码,它应该可以工作。您可以从任何您想要的地方提取“devString”。
这样做的主要危险在于确保所有开发人员都知道哪些参数将传递给他们编写的“字符串”,以及这些参数的数据模型是什么。
| 归档时间: |
|
| 查看次数: |
2649 次 |
| 最近记录: |