这是一个Chrome错误还是我使用“严格使用”和eval无效? [英] Is this a Chrome bug or is my use of "use strict" and eval invalid?

查看:807
本文介绍了这是一个Chrome错误还是我使用“严格使用”和eval无效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码在Chrome浏览器以外的所有浏览器中都会显示ok:

  eval(var outer = 0; function test (){'use strict'; outer = 1;} test(); alert('ok');); 

(试一下 jsfiddle )。

我所做的只是引用一个来自'use strict'函数,全部在 eval 上下文中。 Chrome说:

 未捕获的ReferenceError:outer未定义

注意:当我使用 devtool:'eval' in Webpack

解决方案

为了简化问题: http://jsfiddle.net/rokkkjcs/6/

  eval(var outer = 0;); 
函数test(){'use strict'; outer = 1; }
test();
alert('ok');

而解释是:

非严格的代码可以使用'eval'函数向周围的范围添加新的变量。在浏览器中支持本地JSON之前,'eval'通常(并且不安全)用于从字符串构造对象。构建的对象然后成为周围范围的一部分。在严格模式下,'eval'不能引入新的变量。在严格模式下执行时,以下代码段不会将'bar'变量引入周围范围。注意:如果一个包含'eval'的函数在严格模式下执行,那么'eval'函数内的代码也将在严格模式下执行。



更多信息:< a href =http://cjihrig.com/blog/javascripts-strict-mode-and-why-you-should-use-it/ =nofollow> http://cjihrig.com/blog/javascripts -strict-mode-and-why-you-should-use-it /


This code works alerts "ok" in all browsers except Chrome:

eval("var outer = 0; function test() {'use strict'; outer = 1; } test(); alert('ok');");

(Try it on jsfiddle).

All I'm doing is referencing an outer variable from a 'use strict' function, all in eval context. Chrome says

Uncaught ReferenceError: outer is not defined 

Note: I originally faced it when using devtool: 'eval' in Webpack.

解决方案

To simplify the problem : http://jsfiddle.net/rokkkjcs/6/

eval("var outer=0;");
function test() {'use strict'; outer = 1; } 
test(); 
alert('ok');

And the explanation is :

Non-strict code can use the ‘eval’ function to add new variables to the surrounding scope. Prior to native JSON support in browsers, ‘eval’ was commonly (and unsafely) used to construct objects from strings. The constructed objects then became a part of the surrounding scope. In strict mode, ‘eval’ cannot introduce new variables. When executed in strict mode, the following piece of code will not introduce the ‘bar’ variable into the surrounding scope. Note: if a function containing ‘eval’ is executed in strict mode, then the code inside the ‘eval’ function is also executed in strict mode.

More info : http://cjihrig.com/blog/javascripts-strict-mode-and-why-you-should-use-it/

这篇关于这是一个Chrome错误还是我使用“严格使用”和eval无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆