开发者

Problems with IE9 javascript eval()

Is there any reason for which

eval("(function(x){return x*x;})")

does开发者_JAVA技巧n't return a function with IE9?


It's a bug in the JScript parser. It shouldn't happen in IE9 unless you are in a Compatibility or Quirks mode.

IE8 misinterprets your function expression as a function declaration, causing it to fail to return anything. Previously mentioned in this question.

You can work around it using one of the other typical ways to unconfuse the JScript parser on what constitutes an expression vs a statement, eg:

eval('[function(x){return x*x;}][0]')
eval('0?0:function(x){return x*x;}')


Due to a parser bug, IE's eval cannot directly evaluate a function.

Instead, you should use the Function constructor:

new Function("x", "return x * x;")

Alternatively, you can wrap the eval'd expression in an array:

eval("[ function(x){return x*x;} ][0]")

IE doesn't object to evaling an array or object that contains a function.


eval("(function(x){return x*x;})")

...works just fine in IE9 in normal mode (live proof) (but see below). Doesn't mean it's a good idea (very, very few uses of eval qualify as anything other something than to be avoided), but it does work.

It also works (and should work) in recent versions of Chrome, Firefox, and Opera.

It doesn't seem to work in IE6, IE7, IE8, or IE9 in "compatibility view". That would be a bug (apparently one that's fixed along with about a thousand others with the newer JavaScript engine in IE9), there's nothing wrong with the expression.

You can fix it in earlier versions by forcing the parser to realize it's an expression (live copy):

eval("(0 || function(x){return x*x;})")


I just tested it and

eval("(function(x){return x*x;})")

it returns a function in IE9.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜