JavaScript:严格模式和匿名函数
我的几乎所有 JS 文件都包含在匿名函数中。如果我在匿名函数之外包含 "use strict";
,严格模式是否仍适用于匿名函数?
例如,严格模式是否应用于以下脚本中匿名函数的内部主体:
"use strict";
(function() {
// Is this code running under strict mode?
})();
Nearly all my JS files are wrapped in anonymous functions. If I include "use strict";
outside the anonymous function, is strict mode still applied to the anonymous function?
For example, is strict mode applied to the inner body of the anonymous function in the script below:
"use strict";
(function() {
// Is this code running under strict mode?
})();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 John Resig 的文章,如果您打开严格模式位于文件顶部,它适用于整个文件/脚本。所以是的,这意味着它将在匿名函数中应用。
您还可以将其添加到函数中,在这种情况下,它仅适用于该特定函数。
编辑添加:这是完整规范。相关段落:
According to John Resig's article, if you turn on strict mode at the top of the file, it applies to the entire file/script. So yes, that implies that it would apply within the anonymous function.
You can also add it within a function, in which case it only applies to that specific function.
Edited to add: here's the full specification. One relevant paragraph: