JavaScript eval()笔记

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  坏小仔 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/you0630/archive/2012/08/22/2651135.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值