最近,我通过 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/