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 (使用 importexport 语句)和 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/1335851/

相关文章:

javascript - Bot Connector - Direct Line API 交叉对话?

JavaScript 语法不起作用

javascript - 如何在 JSLINT 中逐个方法地处理未使用的变量?

javascript - 我的 JSON 代码有什么问题?

javascript - js : trigger function after a bunch of events were called

javascript - 使用 fadeIn() 淡化背景图像

javascript - anchor 链接中的 Href 和 onclick 问题

c++ - 前向声明改变功能行为?

linux - 意外标记附近的语法错误

javascript - 如何以 JSLint 认可的方式重写这个 while 循环?