将结果存储为外部对象的一部分时将 eval 转换为函数?
Converting eval to function when storing result as part of external object?
我正在尝试将一些使用 eval 的代码转换为使用基于 these examples 的函数,但我不太了解如何将函数调用的结果存储为现有对象的一部分。我在这里错过了什么?
async function test(){
let obj={"Name":"BOB"}
let ret={};
//eval- works perfectly. stores the result in ret.eval
let evalstr='ret.eval=obj["Name"].toLowerCase()'
eval(evalstr)
//function- 1st attempt- ret not defined
let funcstr='ret.function=obj["Name"].toLowerCase()'
Function('"use strict";return (' + funcstr + ')')();
//2nd attempt-obj not defined
let funcstr='obj["Name"].toLowerCase()'
ret.function=Function('"use strict";return (' + funcstr + ')')();
console.log(ret)
}
test()
我不完全确定您为什么要尝试这样做,并且根据提供的示例我不会推荐它。如果您能提供更多背景信息,我相信有更好的方法可以达到预期的结果。
就是说,如果您想修复代码,您需要使 ret
and/or obj
可用于新创建的 Function
,这涉及将它们声明为参数,然后传入参数。
async function test(){
let obj={"Name":"BOB"}
let ret={};
//eval- works perfectly. stores the result in ret.eval
let evalstr='ret.eval=obj["Name"].toLowerCase()'
eval(evalstr)
//function- 1st attempt- ret not defined
let funcstr='ret.function=obj["Name"].toLowerCase()'
Function('ret', 'obj', '"use strict";return (' + funcstr + ')')(ret, obj);
//2nd attempt-obj not defined
funcstr='obj["Name"].toLowerCase()'
ret.obj=Function('obj', '"use strict";return (' + funcstr + ')')(obj);
console.log(ret)
}
test()
我正在尝试将一些使用 eval 的代码转换为使用基于 these examples 的函数,但我不太了解如何将函数调用的结果存储为现有对象的一部分。我在这里错过了什么?
async function test(){
let obj={"Name":"BOB"}
let ret={};
//eval- works perfectly. stores the result in ret.eval
let evalstr='ret.eval=obj["Name"].toLowerCase()'
eval(evalstr)
//function- 1st attempt- ret not defined
let funcstr='ret.function=obj["Name"].toLowerCase()'
Function('"use strict";return (' + funcstr + ')')();
//2nd attempt-obj not defined
let funcstr='obj["Name"].toLowerCase()'
ret.function=Function('"use strict";return (' + funcstr + ')')();
console.log(ret)
}
test()
我不完全确定您为什么要尝试这样做,并且根据提供的示例我不会推荐它。如果您能提供更多背景信息,我相信有更好的方法可以达到预期的结果。
就是说,如果您想修复代码,您需要使 ret
and/or obj
可用于新创建的 Function
,这涉及将它们声明为参数,然后传入参数。
async function test(){
let obj={"Name":"BOB"}
let ret={};
//eval- works perfectly. stores the result in ret.eval
let evalstr='ret.eval=obj["Name"].toLowerCase()'
eval(evalstr)
//function- 1st attempt- ret not defined
let funcstr='ret.function=obj["Name"].toLowerCase()'
Function('ret', 'obj', '"use strict";return (' + funcstr + ')')(ret, obj);
//2nd attempt-obj not defined
funcstr='obj["Name"].toLowerCase()'
ret.obj=Function('obj', '"use strict";return (' + funcstr + ')')(obj);
console.log(ret)
}
test()