在ECMAScript5中,“使用严格”的范围是什么? [英] In ECMAScript5, what's the scope of "use strict"?

查看:149
本文介绍了在ECMAScript5中,“使用严格”的范围是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

严格模式编译指示在ECMAScript5中有什么范围?

What scope does the strict mode pragma have in ECMAScript5?

"use strict";

我想这样做(主要是因为JSLint没有抱怨):

I'd like to do this (mainly because JSLint doesn't complain about it):

"use strict";

(function () {
  // my stuff here...
}());

但我不确定这是否会破坏其他代码。我知道我可以这样做,这将把pragma的范围扩展到函数...

But I'm not sure if that would break other code or not. I know that I can do this, which will scope the pragma to the function...

(function () {

  "use strict";

  // my stuff here...

}());

但JSLint抱怨它(当启用严格JSLint选项时),因为它认为你'在启用use strict之前重新执行代码。

but JSLint complains about it (when the "strict" JSLint option is enabled) because it thinks you're executing code before you enable "use strict".

这是我的问题。如果我有fileA.js:

Here's my question. If I have fileA.js:

"use strict";
// do some stuff

和fileB.js:

eval( somecodesnippet ); // disallowed by "use strict"

然后按照相同的顺序将它们包含在我的html页面中,将pragma范围限定为文件,或者pragma是否会溢出到fileB中,从而阻止eval执行?

and then include them in my html page in that same order, will the pragma be scoped to the file, or will the pragma bleed over into fileB, thus blocking the eval execution?

推荐答案

编辑看来我错了。请参阅下面的 Jeff Walden的回答

EDIT It appears I was incorrect. Please see Jeff Walden's answer below.

查看此答案相关问题:什么是使用严格在JavaScript中做什么,背后的原因是什么?

Check out this answer to a related question: What does "use strict" do in JavaScript, and what is the reasoning behind it?

尽管有JSLint的抱怨,你可以(并且应该)使用<如果您只希望该函数处于严格模式,请在函数内部使用code>use strict; 。如果在全局上下文中使用它,那么它将强制所有代码处于严格模式。 简答:是的,它会阻止您使用 eval

Despite JSLint's complaints, you can (and should) use "use strict"; inside of a function if you only want that function to be in strict mode. If you use it in the global context then it will force all your code to be in strict mode. Short answer: yes, it will block your use of eval.

这篇关于在ECMAScript5中,“使用严格”的范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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