我注意到 use strict
似乎更常见,如下所示:
(function() {
'use strict';
...
比这个:
'use strict';
(function() {
...
vanilla JS implementation of TodoMVC例如,这样做。
这有什么原因吗?
编辑:我知道整个文件与功能 block 的区别。 TodoMVC 是一个很好的例子,可以说明为什么这个放置对我来说很奇怪,因为它不依赖任何外部库,所以整个“与非严格的第三方玩得很好”在这里并不适用。
最佳答案
在 local
范围内声明它会强制浏览器在 strict-mode
下考虑功能 block 。
您可以对 IIFE
之外的其他代码进行非严格
观察
IIFE
内部:
(function() {
"use strict";
a = 100;
})();
b = 200;
对于整个脚本:
"use strict";
(function() {
try {
a = 100;
} catch (e) {
console.log(e + '');
}
})();
b = 200;
如 docs 中突出显示的那样,
If you are using
strict
mode for entire script, it isn't possible to blindly concatenate non-conflicting scripts. Consider concatenating a strict mode script with a non-strict mode script: the entire concatenation looks strict! The inverse is also true: non-strict plus strict looks non-strict. Concatenation of strict mode scripts with each other is fine, and concatenation of non-strict mode scripts is fine. Only concatenating strict and non-strict scripts is problematic. It is thus recommended that you enable strict mode on a function-by-function basis (at least during the transition period).You can also take the approach of wrapping the entire contents of a script in a function and having that outer function use strict mode. This eliminates the concatenation problem but it means that you have to explicitly export any global variables out of the function scope.
关于javascript - 为什么 'use strict' 通常在 IIFE 之后(而不是在脚本的顶部)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38670872/