有人可以解释为什么这两个函数的行为不同。
代码片段 1:
function operate1(operator) {
return function(x, y) {
return x + operator + y;
}
}
代码片段 2:
function operate2(operator) {
return new Function("x", "y", "return x " + operator + " y;");
}
用法:
adder1 = operate1("+");
adder2 = operate2("+");
adder1(5, 3); // returns "5+3"
adder2(5, 3); // returns 8
我特别好奇为什么 operate2
会计算算术表达式,而我乍一看以为它会将其计算为字符串。这是否与使用 new 运算符将其定义为函数对象有关?
最佳答案
由于运算符是字符串,第一个进行字符串连接
return x + "+" + y;
第二个执行内容评估,因为这就是new Function有效 - 结果类似于 eval但看看这里的差异:Are eval() and new Function() the same thing?
所以声明
new Function("x", "y", "return x " + operator + " y;");
评估了“return x”+operator+“y;”
部分
这是第二个版本,其行为与第一个版本类似
function operate2(operator) {
return new Function("x", "y", "return x +'" + operator + "'+ y;");
}
var adder2 = operate2("+");
alert(adder2(5, 3))
关于javascript - 这两个函数定义有不同的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31402821/