现在的位置: 首页 > 综合 > 正文

javascript的小括号

2013年02月07日 ⁄ 综合 ⁄ 共 1144字 ⁄ 字号 评论关闭

 

今天在写 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> 这个是不会报错的。因为将内容装入一个表达式。

抱歉!评论已关闭.