"strict mode" is a new syntax defined in ECMA-262 Edition 5, indicating that it needs to be executed using strict Javascript syntax. Some used writing methods in the past will throw SyntaxError exceptions, such as:
1. No var declaration before variable
2. Use octal syntax: var n = 023 and var s = "/047"
3. Use with statements
4. Use delete to delete a variable name (not the attribute name): delete myVariable
5. Use eval or arguments as variable name or function name
6. Use future reserved words (maybe used in ECMAScript 6): implements, interface, let, package, private, protected, public, static, and yield as variable names or function names
7. Use function declaration in statement block: if(a<b){ function f(){} }
8. Other errors
8.1. Use two identical attribute names in object sub-face size: {a: 1, b: 3, a: 7}
8.2. Use two identical parameter names in function parameters: function f(a, b, b){}
These are explained in detail below.
1. Why use "strict mode"
The purpose of establishing a "strict model" is mainly as follows:
1. Eliminate some unreasonable and imperfect aspects of Javascript syntax and reduce some weird behaviors;
2. Eliminate some insecurities in the code running and ensure the safety of the code running;
3. Improve compiler efficiency and increase operation speed;
4. Lay the foundation for the new version of Javascript in the future.
"Strict Mode" reflects the more reasonable, safer and more rigorous development direction of Javascript. Mainstream browsers including IE 10 have already supported it, and many major projects have begun to embrace it in full.
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 run in "strict mode". Mastering these contents will help you understand Javascript more carefully and in-depth, making you a better programmer.
This article will give a detailed introduction to the "strict model".
2. Declare "strict mode"
Declaring "strict mode" is simple and has only one statement:
The code copy is as follows: "use strict";
Note: Older browsers will treat it as a normal string and ignore it.
3. Declare the location and contextual relationship of "strict mode"
"strict mode" mainly affects the scope where it is located. If used in functions, it will not turn global scope and other unused functions into "strict mode". That is, the scope of a strict pattern declaration depends on its context. If strict mode is declared in a global context (outside the scope of a function), all code in the program is in strict mode. If a strict pattern is declared in a function, all code in the function is in strict pattern. For example, in the following example, all code is in strict mode, and variable declarations outside the function will cause a syntax error: "Variables are not defined in strict mode". There are two ways to call "strict mode" and are suitable for different occasions.
1.For the entire script file
Put "use strict" in the first line of the script file and the entire script will run in "strict mode". If this line statement is not on the first line, it is invalid and the entire script runs in "normal mode". This requires special attention if code files of different modes are merged into one file.
(Strictly speaking, as long as the statement that produces the actual running result is not preceded, "use strict" may not be on the first line, such as directly following an empty semicolon.)
The code copy is as follows:
<script>
"use strict";
console.log("This is strict mode.");
</script>
<script>
console.log("This is normal mode.");
</script>
The above code indicates that there are two pieces of Javascript code in a web page in turn. The previous script tag is strict mode, the latter one is not.
2. For a single function
Put "use strict" in the first line of the function body, and the entire function runs in "strict mode".
The code copy is as follows:
function strict(){
"use strict";
return "This is a strict pattern.";
}
function notStrict() {
return "This is normal mode.";
}
3. Workarounds for script files
Because the first call method is not conducive to file merging, it is better to borrow the second method and place the entire script file in an anonymous function that is executed immediately.
The code copy is as follows:
(function (){
"use strict";
// some code here
})();
4. Syntax and behavior changes under "strict mode"
"strict mode" has made some changes to the syntax and behavior of Javascript.
1. Explicit declaration of global variables
In normal mode, when using variables, we do not have to use var to declare (explicitly declare), but in Strict Mode, we must use var to declare before using variables, otherwise an error will occur.
The code copy is as follows:
"use strict";
v = 1; // An error is reported, v is not declared
for(i = 0; i < 2; i++) { // An error was reported, i was not declared
}
Therefore, in strict mode, variables must be declared with the var command before use.
2. Static binding
A feature of the Javascript language is that it allows "dynamic binding", that is, which object certain properties and methods belong to, is not 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 attributes and methods belong to is determined during the compilation stage. This will help improve compilation efficiency, make the code easier to read and less accidents.
Specifically, the following aspects are involved.
(1) Use with statements are prohibited
Because the with statement cannot be determined at compile time, which object the attribute belongs to.
The code copy is as follows:
"use strict";
var v = 1;
with (o){ // Syntax error
v = 2;
}
(2) Create an eval scope
In normal mode, the Javascript language has two variable scopes: global scope and function scope. The 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 in the functional 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.
The code copy is as follows:
"use strict";
var x = 2;
console.info(eval("var x = 5; x")); // 5
console.info(x); // 2
3. Enhanced safety measures
(1) Forbid this keyword to point to global objects
The code copy is as follows:
function f(){
return !this;
}
// Return false, because "this" points to the global object, "!this" is false
function f(){
"use strict";
return !this;
}
// Return true, because in strict mode, the value of this is undefined, so "!this" is true.
Therefore, when using the constructor, if you forget to add new, this no longer points to the global object, but reports an error.
The code copy is as follows:
function f(){
"use strict";
this.a = 1;
};
f();// Error, this is not defined
In ordinary function call f(), the value of this will point to the global object. In strict mode, the value of this will point to undefined. When the function is called through call and apply, if the passed this value parameter is a primitive value (string, number, Boolean value) except for null and undefined, then the value of this will become the wrapper object corresponding to the original value. If the value of this value parameter is undefined or null, the value of this will point to the global object. In strict mode, the value of this value is the value of this value parameter, without any type conversion.
(2) Forbidden to traverse the call stack inside the function
The code copy is as follows:
function f1(){
"use strict";
f1.caller; // Report an error
f1.arguments; // Report an error
}
f1();
4. Disable the deletion of variables
Variables cannot be deleted in strict mode. Only the object properties whose configurable is set to true can be deleted.
The code copy is as follows:
"use strict";
var x;
delete x; // Syntax error
var o = Object.create(null, 'x', {
value: 1,
configurable: true
});
delete ox; // Delete successfully
5. Explicit error
In normal mode, if you assign a read-only property of an object, there will be no errors, and it will only fail silently. In strict mode, an error will be reported.
The code copy is as follows:
"use strict";
var o = {};
Object.defineProperty(o, "v", { value: 1, writable: false });
ov = 2; // Report an error
In strict mode, if you assign a property read using the getter method, an error will be reported.
The code copy is as follows:
"use strict";
var o = {
get v() { return 1; }
};
ov = 2; // Report an error
In strict mode, adding new attributes to objects that are prohibited from being extended will result in an error.
The code copy is as follows:
"use strict";
var o = {};
Object.preventExtensions(o);
ov = 1; // Report an error
In strict mode, deleting an undelete property will cause an error.
The code copy is as follows:
"use strict";
delete Object.prototype; // Report an error
6. Rename error
Strict mode has added some syntax errors.
(1) Objects cannot have attributes with duplicate names
In normal mode, if the object has multiple duplicate attributes, the last assigned attribute will override the previous value. In strict mode, this is a syntax error.
The code copy is as follows:
"use strict";
var o = {
p: 1,
p: 2
}; // Syntax error
(2) Functions cannot have parameters with duplicate names
In normal mode, if the function has multiple parameters with duplicate names, it can be read with arguments[i]. In strict mode, this is a syntax error.
The code copy is as follows:
"use strict";
function f(a, a, b) { // Syntax error
return ;
}
7. Octal notation is prohibited
In normal mode, if the first bit of an integer is 0, it means that this is an octal number, such as 0100 equals 64 in decimal. Strict mode prohibits this representation. If the first bit of the integer is 0, an error will be reported.
The code copy is as follows:
"use strict";
var n = 0100; // Syntax error
8. Restrictions of arguments objects
arguments are parameter objects of functions, and strict mode limits its use.
(1) Assigning arguments is not allowed
The code copy is as follows:
"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 tracks the changes in parameters
The code copy is as follows:
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) Use of arguments.callee is prohibited
This means that you can't call yourself inside an anonymous function.
The code copy is as follows:
"use strict";
var f = function() { return arguments.callee; };
f(); // Report an error
9. The function must be declared at the top level
In the future, new versions of Javascript will introduce "block-level scope". To align with the new version, strict mode only allows functions to be declared at the top level of the global scope or function scope. That is, it is not allowed to declare functions within non-function code blocks.
The code copy is as follows:
"use strict";
if (true) {
function f() { } // Syntax error
}
for (var i = 0; i < 5; i++) {
function f2() { } // Syntax error
}
10. Keep words
In order to transition to a new version of Javascript in the future, some reserved words have been added to the strict mode: implements, interface, let, package, private, protected, public, static, yield.
Using these words as variable names will result in an error.
The code copy is as follows:
function package(protected) { // Syntax error
"use strict";
var implements; // Syntax error
}
In addition, the fifth version of ECMAscript also stipulates other reserved words (class, enum, export, extends, import, super), as well as const reserved words added by major browsers, which cannot be used as variable names.