用新关键字声明函数并在javascript中自调用
我遇到了如下代码:用新关键字声明函数并在javascript中自调用,javascript,function-declaration,function-constructor,Javascript,Function Declaration,Function Constructor,我遇到了如下代码: const tempFunc = exp => { return new Function(`return ${exp}`)() } const tempFunc = function(exp) { const compiledFunc = new Function(`return ${exp}`) return compiledFunc() } 第一个问题: 它是自调用函数并返回它吗?。 tempFunc究竟返回什么 第二个问题: 如果我们调用
const tempFunc = exp => {
return new Function(`return ${exp}`)()
}
const tempFunc = function(exp) {
const compiledFunc = new Function(`return ${exp}`)
return compiledFunc()
}
第一个问题:
它是自调用函数并返回它吗?。
tempFunc究竟返回什么
第二个问题:
如果我们调用函数:
let result=tempFunc('3+2')
结果是5。它如何转换字符串并计算结果?当您调用
tempFunc('3+2')
时,它返回新函数(“return 3+2”)()
,该函数将创建一个函数(Function(){return 3+2};
),然后调用该函数
相反,如果tempFunc
如下所示:
const tempFunc = exp => {
return new Function(`return ${exp}`)()
}
const tempFunc = function(exp) {
const compiledFunc = new Function(`return ${exp}`)
return compiledFunc()
}
const tempFunc=exp=>{
返回新函数(`return${exp}`);
}
然后它只返回未调用的新函数,您必须单独调用它:tempFunc('3+2')()代码>
函数构造函数
函数构造函数(newfunction()
)非常有趣;您基本上可以告诉它,作为前n个参数,应该使用哪些参数,最后一个参数是函数体。在您的示例中,新函数没有参数,但我们可以创建一个接受参数的函数:
const tempFunc=num=>{
返回新函数('x','returnx+${num}`)(2);
}
tempFunc(3);
// 5
如果箭头函数让您感到困惑,您也可以这样编写:
const tempFunc = exp => {
return new Function(`return ${exp}`)()
}
const tempFunc = function(exp) {
const compiledFunc = new Function(`return ${exp}`)
return compiledFunc()
}
这:
使用提交的字符串创建新函数对象。字符串(“在您的示例中为3+2”)被编译为函数,就像它是javascript代码一样。然后可以像调用普通javascript函数一样调用此函数对象。这就是这一行末尾的两个妄想狂所做的:
return new Function(`return ${exp}`)() // <-- these call it
return新函数(`return${exp}`)(/),它与eval
非常相似,但计算单个表达式(因为return
)。警告:这个单一表达式可以被绕过,不要用于不安全的输入!这里没有自我调用。