JS面试题,关于eval与new Function

var a,b,c;
(function(){  eval('var b = 2');
  (1, eval)('var c = 3');
  (new Function('var a = 4'))();  document.write('<br>a: ' + a);  document.write('<br>b: ' + b);  document.write('<br>c: ' + c);
})()document.write('<br>a: ' + a);document.write('<br>b: ' + b);document.write('<br>c: ' + c);

执行此段代码后,得到如下结果

a: undefinedb: 2c: 3a: undefinedb: undefined
c: 3

http://codepen.io/quietcoder/...


白衣染霜花
浏览 600回答 1
1回答

噜噜哒

eval能访问上下文,new Function只能构建自己的一个私有作用域。更新,注释一下var a, b, c;(function() {&nbsp; // eval('var b = 2');&nbsp; // 调用当前作用域&nbsp; var b = 2;&nbsp; // (1, eval)('var c = 3');&nbsp; // 逗号操作符,括号表达式,返回的是最后一个挂载在window上的eval&nbsp; window.eval('var c = 3');&nbsp; // (new Function('var a = 4'))();&nbsp; // 申明一个匿名函数&nbsp; (function() {&nbsp; &nbsp; var a = 4;&nbsp; })&nbsp; document.write('<br>a: ' + a);&nbsp; document.write('<br>b: ' + b);&nbsp; document.write('<br>c: ' + c);})()document.write('<br>a: ' + a);document.write('<br>b: ' + b);document.write('<br>c: ' + c);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript