Saturday, April 2, 2011

Javascript Quiz: Question 2


I wanted to convert a string to a function, so I figured this would work:

  var expression = "x * x";
  var f1 = function(x) {
    return eval(expression);
  };
  f1(10);

And it did work, but I didn't want to call eval every time I invoked f1, so I made the outer function part of the eval statement:

  var expression= "x * x";
  expression = "(function (x) { return (" + expression + "); });"
  var f2 = eval(expression);
  f2(20);

This does not work in IE but complains, "Object expected". Specifically:
{
  "name": "TypeError", 
  "message": "Object expected", 
  "number": -2146823281, 
  "description": "Object expected"
}

Question: How can this be done?