js调用字符串函数
利用:Function 构造函数创建一个新的 Function 对象。
//new Function ([arg1[, arg2[, ...argN]],] functionBody)
const sum = new Function('a', 'b', 'return a + b');
console.log(sum(2, 6));//8
参数:
arg1, arg2, ... argN
- 被函数使用的参数的名称必须是合法命名的。参数名称是一个有效的JavaScript标识符的字符串,或者一个用逗号分隔的有效字符串的列表;例如“×”,“theValue”,或“a,b”。
functionBody
- 一个含有包括函数定义的 JavaScript 语句的字符串。
let str = `function bar(){
console.log('执行了')
}`
let fun = new Function('return ' + str)
fun()()