I. Overview
In addition to normal operating mode, ECMAscript 5 adds a second mode of operation: "Strict mode" (strict modes). As the name suggests, this pattern allows JavaScript to run under more stringent conditions.
The purpose of establishing a "strict model" is mainly as follows:
-Eliminate some of the irrational and imprecise JavaScript syntax, and reduce some of the weird behavior;
-Eliminate some of the unsafe code running, to ensure the security of code operation;
-improve compiler efficiency, increase the speed of operation;
-Pave the ground for a new version of JavaScript in the future.
"Strict mode" embodies the more reasonable, safer and more rigorous development of JavaScript, including IE 10, mainstream browsers have supported it, and many big projects have begun to embrace it fully.
On the other hand, the same code, in "Strict mode", may have different running results, and some statements that can be run under normal mode will not run under strict mode. Mastering this content will help you to become a better programmer by understanding JavaScript in a more detailed and in-depth way.
This article describes the "strict mode" in detail.
Ii. Entry Signs
Enter the "strict mode" flag, which is the following line of statements:
"Use strict";
The old version of the browser will ignore it as a line of normal strings.
Third, how to call
There are two ways to invoke "strict mode", which can be applied to different situations.
3.1 for the entire script file
Put "use strict" on the first line of the script file, the entire script will run in "strict mode." If the line statement is not in the first row, it is invalid and the entire script runs in normal mode. This requires special attention if different patterns of code files are merged into one file.
(Strictly speaking, "use strict" may not be in the first line, such as following an empty semicolon, as long as it is not preceded by a statement that produces the actual running result.) )
<script>
"Use strict";
Console.log ("This is strict mode.") ");
</script>
<script>
console.log ("This is normal mode.) ");
</script>
The code above indicates that there are two of JavaScript code in a Web page in sequence. The previous script label is strictly mode, the latter one is not.
3.2 for a single function
Put "use strict" on the first line of the function body, the entire function runs in "strict mode."
function Strict () {
"use strict";
Return "This is strict mode. ";
}
function Notstrict () {return
"This is normal mode. ";
}
3.3 How script files are modified
Because the first invocation method is not conducive to file merging, it is a better practice to use the second method to place the entire script file in an immediately executing anonymous function.
(function () {
"use strict";
Some code here
}) ();
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/