JavaScript eval

eval的基础用法是:执行字符串形式的JavaScript表达式或语句,并返回结果(若是有)javascript

   eval函数返回值

  • 若是没有参数,返回undefined
  • 若是有返回值将返回此值,不然返回undefined
  • 若是为表达式,返回表达式的值
  • 若是为语句返回语句的值
  • 若是为多条语句或表达式返回最后一条语句的值
var json=eval("({sitename:'dreamdu',sitedate:new Date(1980, 12, 17, 12, 0, 0)})");
document.write(json.sitename);
document.write(json.sitedate);
dreamdu
Sat Jan 17 12:00:00 UTC+0800 1981

上面就是eval的用法java

注意:eval 与做用域json

Function能够代替eval执行字符串函数

eval()和Function构造不一样的是eval()能够干扰做用域链,而Function()更安分守己些。无论你在哪里执行 Function(),它只看到全局做用域。ui

  var str = "var num=100;console.log(num);";
        eval(str);  //100
        Function(str)();  //100
new Function(str)(); //100

str是一个方法时:this

  var str = "function hon(){this.name='hongda';this.age=28;}";
        eval(str);
        var str = "function hon2(){this.name='hongda';this.age=28;}";
        Function(str)();

发现Function无效,想一想也是,初始化方法里面怎么写一个方法呢spa

 

str返回时.net

表达式:code

方法:blog

由上面能够看出eval中直接return时都是违法的

能够在内部使用return

eval没有两个参数,就一个有用

eval('x=2;y=3;','c=6;');

返回3

 

http://www.dreamdu.com/javascript/eval/

http://blog.csdn.net/cuixiping/article/details/4823119

相关文章
相关标签/搜索