javascript - These 2 function definitions have different behavior -
can explain why these 2 functions behave differently.
snippet 1:
function operate1(operator) { return function(x, y) { return x + operator + y; } } snippet 2:
function operate2(operator) { return new function("x", "y", "return x " + operator + " y;"); } usage:
adder1 = operate1("+"); adder2 = operate2("+"); adder1(5, 3); // returns "5+3" adder2(5, 3); // returns 8 i particularly curious of why operate2 evaluated arithmetic expression when thought evaluate string @ first glance. have being defined function object new operator?
the first string concatenation due operator being string
return x + "+" + y; the second performs evaluation of content because how new function works - result similar eval have @ differences here: are eval() , new function() same thing?
so statement
new function("x", "y", "return x " + operator + " y;"); has "return x " + operator + " y;" part evaluated
here second version behaving first
function operate2(operator) { return new function("x", "y", "return x +'" + operator + "'+ y;"); } var adder2 = operate2("+"); alert(adder2(5, 3))
Comments
Post a Comment