Friday, March 13, 2009

Cannot define a function with window.eval() in IE 7

Sometimes it's useful to evaluate a string in Javascript. There a variety of reasons why one would want to do that, and it's reasonable to expect that the code would be evaluated in the same way as the code in your .js files. I needed to evaluate some code using the window.eval function in Javascript. It worked fine, until I got an error when the evaluated string tried to define a function.

The following evaluates a string containing javascript that defines a function. It works in Firefox, but not in IE 7:
window.eval( 'function evalfunc3() { alert("evaled!"); }' )
evalfunc3()  // ERROR: "Object expected".  Function is undefined

This is one of those things that's frustrating about making web applications because it just makes it harder to write code that is browser-independent. The code evaluated through the 'eval' function should be treated exactly the same as any other code in your application.

There is a workaround, however. Assigning the function to a property of the window object does work:
window.eval( 'window.evalfunc2 = function() { alert("evaled!"); }' )
evalfunc2()

Since a function is just an object anyway, assigning it to a global variable is equivalent to defining a global function. So, this technique will be browser-independent!

No comments: