开发者

Javascript: eval behavior in IE8

Please consider the example at http://jsfiddle.net/KE8Mv/

HTML

<input type='text' id="log" />

JavaScript

var f = function(){
    if(console && console.log)
        console.log('hello eval issue!');
}.toString();

var f1 = eval('('+f+')');

var logMsg = f1===undefined?'eval returns none':'eval returns function';

$('#log').val(logMsg);

The eval invoke returns function() object in FF and Chrome, but retur开发者_如何学运维ns undefined in IE8:( What might be the issue? How to get the same behavior in all the browsers?


If you really want to do it like this, you can create an anonymous function that will return you the function you need:

var f1 = eval("(function() {return " + f + ";})()");

Edit: Or even simpler (it is only necessary to make the browser consider this an expression with the function being the result of that expression, so we can use the comma operator):

var f1 = eval("0, " + f);

But you might want to consider using the Function constructor that takes the function body as a string.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜