Javascript's strict mode is described in detail

  • 2020-03-30 03:13:35
  • OfStack

Strict mode is the new syntax defined by ecma-262 Edition 5, which means that to execute with strict Javascript syntax, some old conventions throw SyntaxError exceptions, such as:
1. No var declaration before variables
2. Use octal grammar :var n = 023 and var s = "\047"
Use the with statement
Use delete to delete a variable name (instead of a property name):delete myVariable
Use eval or arguments for variable or function names
6. Use future reserved words (perhaps in ECMAScript 6):implements, interface, let, package, private, protected, public, static, and yield as variable or function names
7. Use function declarations in statement blocks :if(a< B) {function f () {}}
8. Other mistakes
8.1. Two identical attribute names are used in the subfaces of the object :{a: 1, b: 3, a: 7}
Function f(a, b, b){}

These are specified below.

1. Why do you use strict mode

The purpose of establishing "strict mode" is as follows:

1. Eliminate some unreasonable and lax aspects of Javascript syntax and reduce some weird behaviors;
2. Eliminate some unsafe aspects of code operation to ensure the security of code operation;
3. Improve compiler efficiency and speed;
4. Lay the groundwork for future versions of Javascript.

On the other hand, the same code, in strict mode, may have different results; Some statements that run in "normal" mode will not run in "strict" mode. Mastering this will help you understand Javascript in more detail and depth, making you a better programmer.

In this article, the strict pattern is described in detail.

2. Declare strict mode

Declaring strict mode is simple with just one statement:

"use strict";

Note: older browsers ignored it as a normal string.

Declare the location and context of strict mode

"Strict mode" mainly affects his scope, and if used in a function, it does not cause global scope and other unused functions to become "strict mode". That is, the scope of a strict schema declaration depends on its context. If a strict pattern is declared in the global context (outside the scope of the function), all the code in the program is in strict mode. If you declare a strict pattern in a function, all the code in the function is in strict mode. For example, in the following example, all the code is in strict mode, and variable declarations outside the function cause syntax errors: "variables are not defined in strict mode." Strict mode has two invocation methods, which are suitable for different situations.

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 is not in the first line, it is invalid and the entire script runs in "normal mode." This is especially important if the code files for the different modes are merged into one file.
(strictly speaking, "use strict" may not be on the first line, such as following an empty semicolon, as long as it is not preceded by a statement that produces actual running results.)


<script>
"use strict";
console.log(" This is the strict model. ");
</script>
<script>
console.log(" This is the normal pattern. ");
</script>

The code above indicates that a web page has two sections of Javascript code in turn. The former script tag is a strict pattern, the latter is not.

2. For a single function

Put "use strict" on the first line of the body of the function, and the entire function runs in strict mode.


function strict(){
"use strict";
return " This is the strict model. ";
}
function notStrict() {
return " This is the normal pattern. ";
}


3. Flexible writing of script files

Because the first method of invocation is not conducive to file consolidation, it is better to borrow the second method and place the entire script file in an anonymous function that executes immediately.

(function (){
"use strict";
// some code here
})();

4. Grammar and behavior changes in strict mode

Strict mode makes some changes to the syntax and behavior of Javascript.

1. Explicit declaration of global variables

In normal Mode, you don't have to declare variables with var (explicitly), but in Strict Mode, you have to declare variables with var before you can use them.


"use strict";
v = 1; //Error reported, v undeclared
for(i = 0; i < 2; i++) { //Error reported, I not declared
}

Therefore, in strict mode, variables must be declared with the var command before they are used.

2. Static binding

One feature of the Javascript language is that it allows for "dynamic binding," where certain properties and methods are determined not at compile time, but at runtime.

Strict mode places some restrictions on dynamic binding. In some cases, only static binding is allowed. That is, the object to which the attributes and methods belong is determined at compile time. This improves compilation efficiency and makes the code easier to read and less unexpected.

Specifically, it involves the following aspects.

(1) prohibit the use of with statement

Because the with statement cannot determine at compile time which object the attribute belongs to.


"use strict";
var v = 1;
with (o){ //Grammar mistakes
v = 2;
}

(2) create the eval scope

In normal mode, the Javascript language has two variable scopes: global and function scopes. The strict pattern creates a third scope: the eval scope.
In normal mode, an eval statement is scoped, depending on whether it is global or functional. In strict mode, the eval statement itself is a scope, and it can no longer generate global variables; the variables it generates can only be used within eval.


"use strict";
var x = 2;
console.info(eval("var x = 5; x")); // 5
console.info(x); // 2

3. Enhanced security measures

(1) forbid this keyword to point to the global object


function f(){
return !this;
}
//Returns false because "this" points to the global object, "! This "is false
function f(){
"use strict";
return !this;
}

// returns true because this is undefined in strict mode, so "! This "to true.
Therefore, when using the constructor, if you forget to add new, this no longer points to the global object, but instead reports an error.

function f(){
"use strict";
this.a = 1;
};
f();//  An error, this undefined 

In ordinary function call f (), the value of this will point to the global object. In strict mode, the value of this will point undefined. When called function through the call and apply if the incoming thisvalue parameter is a null, and undefined except the original value (string, number, Boolean value), then this value will be the original value of the corresponding packing objects, if thisvalue parameter value is undefined or null, the value of this will point to the global object. In strict mode, The value of this is the value of the thisvalue parameter without any type conversion.

(2) it is forbidden to traverse the call stack inside the function


function f1(){
"use strict";
f1.caller; //  An error 
f1.arguments; //  An error 
}
f1();

4. Do not delete variables

Variables cannot be deleted in strict mode. Only the configurable object attribute set to true, to be deleted.


"use strict";
var x;
delete x; //Grammar mistakes
var o = Object.create(null, 'x', {
value: 1,
configurable: true
});
delete o.x; //  Delete the success 

5. Explicit error reporting

In normal mode, an assignment to a read-only property of an object will fail silently without error. In strict mode, an error will be reported.


"use strict";
var o = {};
Object.defineProperty(o, "v", { value: 1, writable: false });
o.v = 2; //  An error 

In strict mode, an assignment to a property read by a getter method results in an error.

"use strict";
var o = {
get v() { return 1; }
};
o.v = 2; //  An error 

In strict mode, an error is reported when a new property is added to an object that is not allowed to be extended.

"use strict";
var o = {};
Object.preventExtensions(o);
o.v = 1; //  An error 

In strict mode, deleting an attribute that cannot be deleted results in an error.

"use strict";
delete Object.prototype; //  An error 

6. Duplicate name error

Strict mode has added some syntax errors.

(1) the object cannot have the property of the same name

In normal mode, if an object has multiple named properties, the last property assigned overrides the previous value. In strict mode, this is a syntax error.


"use strict";
var o = {
p: 1,
p: 2
}; //  Grammar mistakes 

(2) the function cannot have arguments with double names

In normal mode, if the function has multiple arguments with the same name, it can be read using arguments[I]. In strict mode, this is a syntax error.


"use strict";
function f(a, a, b) { //Grammar mistakes
return ;
}

7. Prohibit octal notation

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 notation, and an error is reported if the first integer is 0.


"use strict";
var n = 0100; //Grammar mistakes
8.arguments Restrictions on objects 

Arguments is an argument to a function, and strict mode restricts its use.

(1) arguments are not allowed


"use strict";
arguments++; //Grammar mistakes
var obj = { set p(arguments) { } }; //Grammar mistakes
try { } catch (arguments) { } //Grammar mistakes
function arguments() { } //Grammar mistakes
var f = new Function("arguments", "'use strict'; return 17;"); //Grammar mistakes

(2) arguments no longer tracks parameter changes


function f(a) {
a = 2;
return [a, arguments[0]];
}
f(1); //The normal mode is [2,2]
function f(a) {
"use strict";
a = 2;
return [a, arguments[0]];
}
f(1); //  Strict mode is [2,1]

(3) do not use arguments.callee

This means that you can no longer call yourself inside an anonymous function.


"use strict";
var f = function() { return arguments.callee; };
f(); //  An error 

Functions must be declared at the top level

Future 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 of the global or function scope. That is, functions are not allowed to be declared in non-functional code blocks.


"use strict";
if (true) {
function f() { } //Grammar mistakes
}
for (var i = 0; i < 5; i++) {
function f2() { } //Grammar mistakes
}


The reserved word

To transition to a future version of Javascript, strict mode adds some reserved words: implements, interface, let, package, private, protected, public, static, yield.
Using these words as variable names results in an error.


function package(protected) { //Grammar mistakes
"use strict";
var implements; //Grammar mistakes
}

In addition, ECMAscript version 5 itself stipulates that other reserved words (class, enum, export, extends, import, super), as well as const reserved words added by various browsers, cannot be used as variable names.


Related articles: