javascript的小括号

 

今天在写 JSON数据返回的时候发现。

var a=function(){return "{a:1}";} 不行的

var a=function(){eval("s={a:1}");} 是可以的

var a=function(){eval("({a:1})");} 也是可以的

然后我看了一下http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?

这个连接的数据 最前面都有一个 小括号包含着。

在网上查了一下文章,

http://stackoverflow.com/questions/964397/why-does-javascripts-eval-need-parentheses-to-eval-json-data

具体如下:

It is because, putting the brackets in there effectively creates the statement:

stuff = eval('return ' + data_from_the_wire + ';');

If you were to eval without the parentheses, then the code would be evaluated, and if you did have any named functions inside it those would be defined, but not returned.

Take as an example the ability to call a function just as it han been created:

(function() { alert('whoot'); })()

Will call the function that has just been defined. The following, however, does not work:

function() { alert('whoot'); }()

So we see that the parentheses effectively turn then code into an expression that returns, rather than just code to run.

 

意思:

小括号在Eval 表示。定义并且返回。

如:这样的代码效果:stuff = eval('return ' + data_from_the_wire + ';');

但如果 你的小括号里面有函数 那么只会定义,不会返回。

所以我们看,小括号的效果,将代码装入一个表达式返回。而不只是执行。

所以我们平时可以看到。

<script>{a:1}</script> 这个是报错。

<script>({a:1})</script> 这个是不会报错的。因为将内容装入一个表达式。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值