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

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -