1. Overview
In addition to the normal operating mode, ECMAscript 5 adds a second operating mode: "strict mode". As the name suggests, this mode makes Javascript run under stricter conditions.
The purpose of establishing "strict mode" is mainly as follows:
- Eliminate some unreasonable and imprecise aspects of Javascript syntax, and reduce Some weird behaviors;
-Eliminate some unsafe aspects of code running and ensure the safety of code running;
-Improve compiler efficiency and increase running speed;
- Pave the way for new versions of Javascript in the future.
"Strict Mode" embodies the more reasonable, safer and more rigorous development direction of Javascript. Mainstream browsers, including IE 10, already support it, and many large projects have begun to fully embrace it. it.
On the other hand, the same code may have different running results in "strict mode"; some statements that can be run in "normal mode" will not be able to be run in "strict mode" run. Mastering these contents will help you understand Javascript in more detail and make you a better programmer.
This article will introduce "strict mode" in detail.
2. Entry sign
The sign to enter "strict mode" is the following line:
"use strict";
Older versions of browsers will treat it as a line of ordinary strings and ignore it.
3. How to call
There are two calling methods for "strict mode", which are suitable for different occasions.
3.1 For the entire script file
Put "use strict" on the first line of the script file, and the entire script will run in "strict mode". If this line of statement is not the first line, it has no effect and the entire script runs in "normal mode". This needs special attention if code files from different modes are merged into one file.
(Strictly speaking, as long as it is not preceded by a statement that produces actual operating results, "use strict" does not need to be on the first line, such as directly following an empty semicolon.)
<script><br> "use strict";<br> console.log("This is strict mode.");<br> </script>
<script><br> console.log("This is normal mode.");kly, it's almost 2 years ago now. I can admit it now - I run it on my school's network that has about 50 computers.<br> </script>
The above code indicates that there are two pieces of Javascript code in a web page. The former script tag is in strict mode, but the latter one is not.
3.2 For a single function
Put "use strict" on the first line of the function body, and the entire function will run in "strict mode".
function strict(){
"use strict";
return "This is strict mode.";
}function notStrict() {
return "This is the normal mode.";
}
3.3 Alternative way of writing script files
Because the first calling method is not conducive to Files are merged, so a better approach is to borrow the second method and put the entire script file in an anonymous function that is executed immediately.
(function (){
"use strict";// some code here
})();
4. Syntax and behavior changes
Strict mode has made some changes to the syntax and behavior of Javascript.
4.1 Explicit declaration of global variables
In normal mode, if a variable is assigned a value without being declared, the default is a global variable. Strict mode prohibits this usage and global variables must be declared explicitly.
"use strict";
v = 1; // Error, v is not declared
for(i = 0; i < 2; i ) { // Error, i is not declared
}
Therefore, in strict mode, variables must first use the var command Declare it before using it.
4.2 Static Binding
One of the characteristics of the Javascript language is that it allows "dynamic binding", that is, which object some properties and methods belong to, not in which object they belong to. It is determined at compile time, but at runtime.
Strict mode places some restrictions on dynamic binding. In some cases, only static binding is allowed. In other words, which object the properties and methods belong to is determined during the compilation stage. This will help improve compilation efficiency, make the code easier to read, and cause fewer surprises.
Specifically, it involves the following aspects.
(1) It is forbidden to use the with statement
Because the with statement cannot determine at compile time which object the attribute belongs to.
"use strict";
var v = 1;
with (o){ // Syntax error
v = 2;
}
(2) Create eval scope
In normal mode, the Javascript language has two variable scopes (scope): global scope and function Scope. Strict mode creates a third scope: eval scope.
In normal mode, the scope of the eval statement depends on whether it is in the global scope or the function scope. In strict mode, the eval statement itself is a scope and can no longer generate global variables. The variables it generates can only be used inside eval.
"use strict";
var x = 2;
console.info(eval("var x = 5; x")); // 5
console.info(x); // 2
4.3 Enhanced security measures
(1) Prohibited The this keyword points to the global object
Function f(){
Return !this;
}
// Returns false because "this" points to the global object, "!this" is falseFunction f(){
"use strict";
return !this;
}
// Return true, because in strict mode, this The value is undefined, so "!this" is true.
Therefore, when using the constructor, if you forget to add new, this will no longer point to the global object, but an error will be reported.
Function f(){
"use strict";
this.a = 1;
};
f();//Error, this is undefined
(2) It is forbidden to traverse the call stack inside the function
function f1(){
"use strict";
f1.caller; // Error report
f1.arguments; // Error report
}
f1();
4.4 Prohibiting deletion of variables
Variables cannot be deleted in strict mode. Only object properties with configurable set to true can be deleted.
"use strict";
var x;
delete x; // Syntax error
var o = Object.create(null , {'x': {
value: 1,
configurable: true
}});delete o.x; //Delete successfully
4.5 Explicit error reporting
In normal mode, assigning a value to a read-only property of an object will not report an error, but will fail silently. In strict mode, an error will be reported.
"use strict";
var o = {};Object.defineProperty(o, "v", { value: 1, writable: false });
o.v = 2; // Error
In strict mode, an error will be reported when assigning a value to an attribute read using the getter method.
"use strict";
var o = {
get v() { return 1; }};
o.v = 2 ; // Error
In strict mode, an error will be reported when adding new attributes to an object that is prohibited from expansion.
"use strict";
var o = {};
Object.preventExtensions(o);
o.v = 1; / / Report an error
In strict mode, if you delete an attribute that cannot be deleted, an error will be reported.
"use strict";
delete Object.prototype; // Error report
4.6 Duplicate name errors
Strict mode has added some new syntax errors.
(1) The object cannot have attributes with the same name
In normal mode, if the object has multiple attributes with the same name, the last assigned attribute will overwrite the previous one. value. In strict mode, this is a syntax error.
"use strict";
var o = {
p: 1,
p: 2
}; // Syntax error
(2) Functions cannot have parameters with duplicate names
In normal mode, if a function has multiple parameters with duplicate names, you can use arguments[i] to read them. In strict mode, this is a syntax error.
"use strict";
function f(a, a, b) { // Syntax error
return ;
}
4.7 Prohibit octal representation
In normal mode, if the first digit of an integer is 0, it means that it is an octal number. For example, 0100 is equal to 64 in decimal. . Strict mode prohibits this representation, the first bit of the integer is 0, and an error will be reported.
"use strict";
var n = 0100; // Syntax error
4.8 Limitations of arguments object
arguments is the parameter object of the function, and strict mode restricts its use.
(1) Assignment of arguments is not allowed
"use strict";
arguments; // Syntax error
var obj = { set p(arguments) { } }; // Syntax error
try { } catch (arguments) { } // Syntax error
function arguments() { } // Syntax error
var f = new Function("arguments", "'use strict'; return 17;"); // Syntax error
(2 ) arguments no longer track parameter changes
function f(a) {
a = 2;
return [a, arguments[0] ];
}
f(1); // Normal mode is [2,2]
function f(a) {
"use strict";
a = 2;
return [a, arguments[0]];
}
f(1); // Strict mode is [2,1]
(3) It is forbidden to use arguments.callee
This means that you cannot call itself inside an anonymous function.
"use strict";
var f = function() { return arguments.callee; };
f(); // Error report
4.9 Functions must be declared at the top level
In the future, new versions of Javascript will introduce "block-level scope". In order to keep in line with the new version, strict mode only allows functions to be declared in the global scope or the top level of the function scope. That is, it is not allowed to declare functions within a non-function code block.
"use strict";
if (true) {
function f() { } // Syntax error
}
for (var i = 0; i < 5; i ) {
function f2() { } // Syntax error
}
##4.10 Reserved words
In order to prepare for future Javascript updates Version transition, strict mode adds some new reserved words: implements, interface, let, package, private, protected, public, static, yield. Using these words as variable names will result in an error.Function package(protected) { // Syntax error "use strict"; var implements; // Syntax error }In addition, the fifth version of ECMAscript itself also stipulates other reserved words (class, enum, export, extends, import, super), as well as const reserved words added by major browsers, which are also It cannot be used as a variable name.
5. Reference links
- MDN, Strict mode- Dr. Axel Rauschmayer, JavaScript's strict mode: a summary
- Douglas Crockford, Strict Mode Is Coming To Town
Related code analysis of php to implement login function
Explanation of JavaScript-related content
Explanation on the basics of HTML
The above is the detailed content of Detailed explanation of Javascript strict mode. For more information, please follow other related articles on the PHP Chinese website!