English 中文(简体)
评价JSON strings - eval() vs new Function(引文)
原标题:Evaluating JSON strings - eval() vs. new Function() [duplicate]
This question already has answers here:
Closed 11 years ago.

Possible Duplicate:
jQuery uses (new Function(“return ” + data))(); instead of eval(data); to parse JSON, why?

鉴于显示有效载荷的,这两种平线方法之间存在差异:

var str, obj;

str =  {"prop":"value"} ;

// method 1:
obj = eval(  (  + str +  )  );

// method 2:
obj = ( new Function(  return (  + str +  );  ) )();

我注意到,j Query使用第二种方法(在缺乏建筑的JSON教区的情况下)。 我想他们为什么不使用第一种方法。 为什么在你能够使用<代码>eval(<>/code>时,便产生功能反对和援引功能?

Please close as exact duplicate

问题回答

<代码>eval在所申报的范围内执行。 <代码> 功能产生新的功能标的,其范围有其自己的范围,并提到可称为的功能。

举这个例子:

var x = 123;
var y;
function TestEval()
{
   var y = 1;
   Function("window.alert( Global x:   + x);")(); //Prints 123
   Function("window.alert( Local y:   + y);")(); //Prints undefined

   eval("window.alert( Global x:   + x);"); //Prints 123
   eval("window.alert( Local y:   + y);"); //Prints 1
}

TestEval();

前两封功能电话将打印123。 (x未定义的的全球价值,y

两个<代码>eval功能将印刷123<>/code>和1。 (y的当地价值)。 这是因为<代码>eval可在当地查阅其正在实行的关闭。 这些行为(以及以下事实:eval <>/code>完全不可靠,inconsistent, 可在许多浏览器中加以利用。

<>说明: 以上第8条所测试的法典:

使用<代码>eval是邪恶的,因为安全漏洞很多。 你们正在全球范围内执行守则。 <条码>功能通过在其本身范围内执行而有所不同。 但“职能”blog 显示:Function在FF2中几乎是2x的。

Edit:我不敢肯定,如果你执行<条码>文件>,地点=“Bbad-url”,则会继续使用<条码>功能<<>代码>实施。

在全球范围,在“;”之后,由于<代码>return <>/code>,该编码也赢得了任何执行,从而帮助了一条轨道。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.