坏小仔

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

The eval() method will return the result of the last expression in the passed code string.
For example, if we were to call:
eval('3+4;5+6')
the result would be 11.
It should be noted that anything that isn't a simple variable, primitive, or assignment will
actually need to be wrapped in a parentheses in order for the correct value to be returned.
For example, if we wanted to create a simple object using eval(), we might be tempted to
write:
var o = eval('{ninja: 1}');
But that wouldn’t do what we want. Rather, we’d need to surround the object literal with
parentheses as follows:
var o = eval('({ninja: 1})');

*****

<script type="text/javascript">
var o = eval("({name:'Ninja'})"); #1
assert(o != undefined,"o was created");
assert(o.name === "Ninja",
"and with the expected property");
var fn = eval("(function(){return 'Ninja';})"); #2
assert(typeof fn === 'function',
"function created");
assert(fn() === "Ninja",
"and returns expected value" );
</script>
#1 Creates an object
#2 Creates a function

If you ran this test under Internet Explorer 8 or earlier, you may have gotten a nasty
surprise. Versions of IE prior to IE9 have a problem executing that particular syntax. We are
forced to use some Boolean-expression trickery to get the call to eval() to execute
correctly. The following shows a technique found in jQuery to create a function using eval()
in broken versions of IE.
var fn = eval("false||function(){return true;}");
assert(fn() === true,
"The function was created correctly.");
This particular issue is fixed in IE9.


Just as when we create a function in a particular scope using “normal” means, functions
created with eval() inherit the closure of that scope – a ramification of the fact that
eval() executes within the local scope.
It turns out that if we don't need that additional closure, there's another alternative that
we can make use of.

posted on 2012-08-22 16:57  坏小仔  阅读(154)  评论(0编辑  收藏  举报