javascript - "use strict"在 JavaScript 中做了什么,背后的原因是什么?

标签 javascript syntax jslint use-strict

最近,我通过 Crockford 的 JSLint 运行了一些 JavaScript 代码。 ,它给出了以下错误:

Problem at line 1 character 1: Missing "use strict" statement.


搜索了一下,发现有人加了"use strict";进入他们的 JavaScript 代码。一旦我添加了语句,错误就停止出现了。不幸的是,谷歌没有透露这个字符串声明背后的大部分历史。当然,这一定与浏览器如何解释 JavaScript 有关,但我不知道会产生什么影响。
那么"use strict";是什么?所有关于,它意味着什么,它仍然相关吗?
当前浏览器是否响应 "use strict";字符串还是供将来使用?

最佳答案

ES6 模块更新
内部 native ECMAScript modules (使用 import export 语句)和 ES6 classes , 严格模式始终启用,不能禁用。
原始答案
您可能会对这篇关于 Javascript 严格模式的文章感兴趣:John Resig - ECMAScript 5 Strict Mode, JSON, and More
引用一些有趣的部分:

Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions.


和:

Strict mode helps out in a couple ways:

  • It catches some common coding bloopers, throwing exceptions.
  • It prevents, or throws errors, when relatively "unsafe" actions are taken (such as gaining access to the global object).
  • It disables features that are confusing or poorly thought out.

另请注意,您可以将“严格模式”应用于整个文件......或者您只能将其用于特定功能(仍然引用 John Resig 的文章):
// Non-strict code...

(function(){
  "use strict";

  // Define your library strictly...
})();

// Non-strict code...
如果您必须混合旧代码和新代码,这可能会有所帮助;-)
所以,我想它有点像 "use strict" 您可以在 Perl 中使用(因此得名?):它通过检测更多可能导致损坏的事物来帮助您减少错误。
严格模式现在是 supported by all major browsers .

关于javascript - "use strict"在 JavaScript 中做了什么,背后的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45849408/

相关文章:

javascript - 使用 onClick 更新数据库(NewB)

javascript - webpack-dev-server 不编译子文件夹中的 React 组件

javascript - 为什么 await* 从 async/await 提案中移除?

types - 为什么 Elm 使用 '++' 运算符来连接字符串?

syntax - 为什么这个 Haskell 不正确?

perl - 围绕变量的花括号

javascript - 如何分析/减少 html 页面渲染时间?

javascript - Jslint 不喜欢 !==,似乎更喜欢 ===,与 typeof 的关系

emacs:我可以在模式 Hook fn 中设置 compilation-error-regexp-alist 吗?

javascript - 为什么VS中jsLint生成: A '<noscript>' must be within '< body head noframes >?