javascript - 为什么 'use strict' 通常在 IIFE 之后(而不是在脚本的顶部)?

标签 javascript

我注意到 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/

相关文章:

javascript - jQuery:自动文本框中的总值

javascript - 如何在html模板中的数字中插入逗号?

javascript - 通过 firebase 云消息从 Android 应用程序向 Web 应用程序发送通知

Javascript - 创建一个增量为 30 步的 for 循环

javascript - 如何创建一个将参数传递给 REST Web 服务的 Controller

javascript - 您如何检测和识别 Javascript/jQuery 冲突?

javascript - ipad 的 jquery html textarea 插件

javascript - 获取日期数组的时间戳值

javascript - 当我按相同的属性进行过滤时,如何查看已过滤的对象数组中属性的变化?

javascript - 如何使用 jQuery 对所有 future 元素进行 ReplaceWith() ?