Evaluates a string and executes it as if it was script code

 

"动态解析!"

 

找了下面两个例子,对eval()方法有了些感觉.感觉这个东东像是那种病毒,它自己可以自我复制,又像是又一套执行环境,它里面可以执行String类型的句子,

<html>
<body>

<script type="text/javascript">

    try{
        alert("Result: "+eval(prompt("Enter an expression: "," ")) );
    }catch(exception){
        alert(exception);
    }

</script>

</body>
</html>

在这个网页面里实验"http://www.w3schools.com/DHTML/tryit.asp?filename=trydhtml_randombanner"
<html>
<body>

        <script type="text/javascript">
            image0="/banners/w3schools.gif";
            href0="/default.asp";
            alt0="W3Schools.com";

            image1="/banners/rd_htmlref.jpg";
            href1="http://www.w3schools.com/html/html_reference.asp";
            alt1="HTML Reference";

            image2="/banners/rd_xhtml.jpg";
            href2="http://www.w3schools.com/xhtml/default.asp";
            alt2="ASP Free";

            len=3;

            now=new Date();
            now=now.getSeconds();
            rnd=now%len;

            image=eval("image"+rnd);
            href=eval("href"+rnd);
            alt=eval("alt"+rnd);

            document.write("I am Here:" + image + "<hr> " + rnd + "<hr> " );

            document.write("<a href='" + href + "'>");
            document.write("<img src='" + image + "' alt='" + alt + "'></a>");    
        </script>

    <h3>Refresh this page to see the banner change</h3>

</body>
</html>


image=eval("image"+rnd);
href=eval("href"+rnd);
alt=eval("alt"+rnd);
改为:
image="image"+rnd;
href="href"+rnd;
alt="alt"+rnd;

后,出事了,

现象如下:
这是改后的显示:"I am Here: image2",改前的显示为"I am Here: /banners/w3schools.gif".

自己拼的字符串仅仅是一个干巴巴的字符串,而用eval()后的字符串就有了指针的灵性!!!

 

 

现在感觉这个eval()就像Java里的源代码调用自己的.class一样,eval()自己可以自我编译.

可这个与JSON又有什么关系呢?还是感觉不出什么必然的联系.

评论
hax 2008-03-26
你对eval的认识有误。大多数时候都不应该使用eval。文中的例子是如此,jquery的例子也是如此。没有必要迷信jquery。
rmn190 2008-03-25
看jQuery.js的源码发现有如下的应用:
if ( typeof fn == "string" )
fn = eval("false||function(a,i){return " + fn + ";}");
rmn190 2008-03-25
在这个网页里发现了下面的一条:
eval("document.onmousedown = OnMouseDownHandler;");

比Java的反射灵活多了!
rmn190 2008-03-25
The eval() function in javascript is a way to run arbitrary code at run-time. In almost all cases, eval should never be used. If it exists in your page, there is almost always a more correct way to accomplish what you are doing. For example, eval is often used by programmers who do not know about using Square Bracket Notation.

http://www.javascripttoolbox.com/bestpractices/#squarebracket
发表评论

您还没有登录,请登录后发表评论