The strict mode of JavaScript strict mode introduces _javascript techniques in detail

Source: Internet
Author: User
Tags eval reserved

The "strict mode" (Strict mode) is the new syntax defined by ECMA-262 Edition 5, which means that you want to execute with a strict JavaScript syntax, and some of the past idioms will throw syntaxerror exceptions, such as:
1. Variables not declared with Var before
2. Use octal syntax: var n = 023 and var s = "\047"
3. Use with statement
4. Delete a variable name (instead of a property name) using delete:d elete myvariable
5. Use eval or arguments as variable name or function name
6. Use future reserved words (which may be used in ECMAScript 6): Implements, interface, let, package, private, protected, public, static, and yield as variable or function names
7. Use a function declaration in a statement block: if (a<b) {function f ()}}
8. Other errors
8.1. Use two identical property names in the object's child surface: {a:1, B:3, A:7}
8.2. Use two identical parameter names in function parameters: function f (A, B, b) {}

These are specifically described below.

One, why use "strict mode" (the strict Mode)

The purpose of establishing a "strict model" is mainly as follows:

1. Eliminate some unreasonable and imprecise JavaScript grammar, reduce some of the strange behavior;
2. Eliminate some unsafe code running, ensure the safety of code operation;
3. Improve compiler efficiency, increase running speed;
4. 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. declaring "strict model" (Strict mode)

Declaring "strict mode" (strict mode) is simply one statement:

Copy Code code as follows:
"Use strict";

Note: The old version of the browser will be ignored as a line of normal strings.

Iii. declaring the position and context relationship of "strict mode" (strict modes)

"Strict mode" (strict mode) primarily affects the scope he is in, and if used in a function, it does not make global scope and other unused functions "strict mode" (Strict mode). This means that the scope of the strict mode declaration depends on its context. If you declare a strict pattern in a global context (outside the scope of a function), all 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 code is in strict mode, and a variable declaration outside of a function causes a syntax error: "No variables are defined in strict mode." There are two ways to invoke "strict mode", which can be applied to different situations.

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.) )

Copy Code code as follows:

<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.

2. For a single function

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

Copy Code code as follows:

function Strict () {
"Use strict";
Return "This is strict mode. ";
}
function Notstrict () {
Return "This is normal mode. ";
}


3. scripting file Adaptation

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.
Copy Code code as follows:

(function () {

"Use strict";
Some code here

})();

Iv. syntax and behavioral changes under "strict mode" (Strict mode)

"Strict mode" (Strict mode) has made some changes to the syntax and behavior of JavaScript.

1. Explicit declaration of global variables

In normal mode, we do not have to use VAR declaration (Explicit declaration) when using variables, but in strict mode, the variables must be declared with Var before they can be used, otherwise there will be errors.

Copy Code code as follows:

"Use strict";
v = 1; Error, v not declared
for (i = 0; i < 2; i++) {//error, I not stated
}

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 belong to exactly one object, not at compile time, but at runtime (runtime).

Strict mode has some restrictions on dynamic binding. In some cases, only static bindings are allowed. That is, the attributes and methods belong to which object and are determined at compile time. This helps to improve the efficiency of the compilation, but also makes the code easier to read, less accidents.

Specifically, the following aspects are involved.

(1) Prohibit use with statement

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

Copy Code code as follows:

"Use strict";
var v = 1;
With (o) {//Syntax error
v = 2;
}

(2) Creating an eval scope

In normal mode, the JavaScript language has two variable scopes (SCOPE): global scope and function scope. The rigorous model creates a third scope: the eval scope.
In normal mode, the scope of the Eval statement depends on whether it is in the global scope or in the function scope. In strict mode, the Eval statement itself is a scope that can no longer generate a global variable, and its generated variables can only be used within the eval.

Copy Code code as follows:

"Use strict";
var x = 2;
Console.info (eval ("var x = 5; X ")); 5
Console.info (x); 2

3. Enhanced security measures

(1) Prohibit the This keyword from pointing to a global object

Copy Code code as follows:

function f () {
return!this;
}
Returns false because "this" points to a global object, "!this" is false
function f () {
"Use strict";
return!this;
}

Returns true because the value of this is undefined in strict mode, so "!this" is true.
Therefore, when you use a constructor, if you forget to add new,this no longer point to the global object, it is an error.
Copy Code code as follows:

function f () {

"Use strict";
THIS.A = 1;
};
f ();//error, this is undefined


In the normal function call F (), the value of this will point to the global object. In strict mode, this value points to undefined. When a function is called by call and apply, If the incoming Thisvalue parameter is an original value (string, number, Boolean) except for null and undefined, the value of this will be the wrapper object for that original value, if the value of the Thisvalue parameter 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 conversions.

(2) prohibit traversing the call stack inside the function

Copy Code code as follows:

Function F1 () {

"Use strict";
F1.caller; Error
f1.arguments; Error
}
F1 ();

4. Prohibit deletion of variables

You cannot delete a variable in strict mode. Only object properties that are set to true configurable can be deleted.

Copy Code code as follows:

"Use strict";
var x;
Delete x; Syntax error
var o = object.create (null, ' X ', {
Value:1,
Configurable:true
});
Delete o.x; Delete Succeeded

5. An explicit error

In normal mode, the read-only property of an object is assigned, without an error, and silently fails. In strict mode, there will be an error.

Copy Code code as follows:

"Use strict";
var o = {};
Object.defineproperty (O, "V", {value:1, writable:false});
O.V = 2; Error

In strict mode, an error is assigned to an attribute that is read by using the Getter method.
Copy Code code as follows:

"Use strict";
var o = {
Get V () {return 1;}
};
O.V = 2; Error

In strict mode, adding a new attribute to an object that is not extensible will cause an error.
Copy Code code as follows:

"Use strict";
var o = {};
Object.preventextensions (o);
O.V = 1; Error

In strict mode, deleting a property that cannot be deleted will cause an error.
Copy Code code as follows:

"Use strict";
Delete Object.prototype; Error

6. Duplicate name error

Strict mode has added some syntax errors.

(1) Objects cannot have properties with duplicate names

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

Copy Code code as follows:

"Use strict";
var o = {
P:1,
P:2
}; Syntax error

(2) function cannot have parameter with duplicate name

In normal mode, a function can be read with arguments[i if it has more than one parameter with the same name. In strict mode, this is a syntax error.

Copy Code code as follows:

"Use strict";
function f (A, A, b) {//Syntax error
return;
}

7. Prohibition of octal notation

In normal mode, the first digit of an integer if it is 0 indicates that this is the number of octal, such as 0100 equals decimal 64. Strict mode prohibits this notation, the first digit of the integer is 0, will be an error.

Copy Code code as follows:

"Use strict";
var n = 0100; Syntax error
Limitations of 8.arguments objects

Arguments is the parameter object of a function, and strict mode restricts its use.

(1) Do not allow the arguments to assign value

Copy Code code 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 track the change of parameters

Copy Code code 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) prohibit the use of Arguments.callee

This means that you cannot invoke itself within the anonymous function.

Copy Code code as follows:

"Use strict";
var f = function () {return arguments.callee;};
f (); Error

9. Function must be declared at the top level

A new version of JavaScript in the future introduces "block-level scopes." In order to be in line 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, you are not allowed to declare a function within a block of code that is not a function.

Copy Code code as follows:

"Use strict";
if (true) {
function f () {}//Syntax error
}
for (var i = 0; i < 5; i++) {
function F2 () {}//Syntax error
}


10. Reserved words

In order to transition to a new version of JavaScript in the future, strict mode adds some reserved words: Implements, interface, let, package, private, protected, public, static, yield.
Using these words as a variable name will cause an error.

Copy Code code as follows:

function package (Protected) {//Syntax error
"Use strict";
var implements; Syntax error
}

In addition, the fifth edition of ECMAScript itself also stipulates that other reserved words (class, enum, export, extends, import, super), as well as the const reserved words added by the major browsers themselves, cannot be used as variable names.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.