我有一些 JavaScript 函数定义存储在字符串中。
"function firstFun() {
return 'some text';
}
function secondFun() {
console.log(firstFun())
}"
是否可以像其他函数一样访问和调用这些函数? 喜欢:
var text = firstFun(); // return 'some text'
secondFun(); // print 'some text'
最佳答案
如果您已将 JS 代码存储在字符串中,则必须 eval
它(这是一个危险的操作 - 如果您正在运行不受信任的代码,正如 T.J. Crowder 所澄清的那样):
const code = `
function firstFun() {
return 'some text';
}
function secondFun() {
console.log(firstFun())
}
`;
eval(code);
关于javascript - JavaScript 中从字符串获取函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51706392/