What does quot;use strictquot; do in JavaScript, and what is the reasoning behind it?(“使用严格是什么意思?在 JavaScript 中做,它背后的原因是什么?)
问题描述
Recently, I ran some of my JavaScript code through Crockford's JSLint, and it gave the following error:
Problem at line 1 character 1: Missing "use strict" statement.
Doing some searching, I realized that some people add "use strict";
into their JavaScript code. Once I added the statement, the error stopped appearing. Unfortunately, Google did not reveal much of the history behind this string statement. Certainly it must have something to do with how the JavaScript is interpreted by the browser, but I have no idea what the effect would be.
So what is "use strict";
all about, what does it imply, and is it still relevant?
Do any of the current browsers respond to the "use strict";
string or is it for future use?
Update for ES6 modules
Inside native ECMAScript modules (with import
and export
statements) and ES6 classes, strict mode is always enabled and cannot be disabled.
Original answer
This article about Javascript Strict Mode might interest you: John Resig - ECMAScript 5 Strict Mode, JSON, and More
To quote some interesting parts:
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.
And:
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.
Also note you can apply "strict mode" to the whole file... Or you can use it only for a specific function (still quoting from John Resig's article):
// Non-strict code...
(function(){
"use strict";
// Define your library strictly...
})();
// Non-strict code...
Which might be helpful if you have to mix old and new code ;-)
So, I suppose it's a bit like the "use strict"
you can use in Perl (hence the name?): it helps you make fewer errors, by detecting more things that could lead to breakages.
Strict mode is now supported by all major browsers.
这篇关于“使用严格"是什么意思?在 JavaScript 中做,它背后的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“使用严格"是什么意思?在 JavaScript 中做,它背后的原因是什么?
基础教程推荐
- 在for循环中使用setTimeout 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 动态更新多个选择框 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01