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

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

问题描述

严格模式 pragma 在 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...
}());

但我不确定这是否会破坏其他代码.我知道我可以做到这一点,这会将编译指示范围限定为函数...

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 选项时),因为它认为您在启用使用严格"之前正在执行代码.

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:

and 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?

推荐答案

EDIT 看来我错了.请参阅Jeff Walden 在下方的回答.

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

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

尽管 JSLint 有抱怨,但如果您只希望函数处于严格模式,您可以(并且应该)在函数内部使用 "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 中,“use strict"的范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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