Strict Javascript mode-detailed introduction to strictmode-javascript skills

Source: Internet
Author: User
This article mainly introduces the strict mode strictmode of Javascript, focuses on the use of the strict mode and the changes in the javascript syntax after the use of strictmode, if you need a friend, refer to the strict mode (strict mode) is a new syntax defined by ECMA-262 Edition 5, which means to use strict Javascript syntax to execute, some commonly used methods will throw a SyntaxError exception, for example:
1. var is not declared before the variable
2. Use the octal Syntax: var n = 023 and var s = "\ 047"
3. Use the with statement
4. Use delete to delete a variable name (instead of the attribute name): delete myVariable
5. Use eval or arguments as the variable name or function name
6. Use future reserved words (may be used in ECMAScript 6): implements, interface, let, package, private, protected, public, static, and yield as variable names or function names
7. Use the function declaration in the statement block: if ( 8. Other errors
8. 1. Use two identical attribute names in the object subsurface quantity: {a: 1, B: 3, a: 7}
. Two identical parameter names are used in the function parameters: function f (a, B, B ){}

These are described below.

I. Why strict mode)

The purpose of setting up a strict model is as follows:

1. Eliminate unreasonable and not rigorous Javascript syntax and reduce some weird behavior;
2. Eliminate some unsafe aspects of code running to ensure the security of code running;
3. Improve compiler efficiency and speed;
4. lay the groundwork for future new versions of Javascript.

"Strict mode" reflects the more reasonable, safer, and more rigorous development direction of Javascript. Mainstream browsers, including IE 10, have supported it, many large projects have begun to embrace 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, it cannot run in "strict mode. Understanding this content helps you understand Javascript in a more detailed and in-depth manner and turn you into a better programmer.

This article will detail the "strict mode.

Ii. strict mode)

Declaring strict mode is very simple. There is only one statement:

The Code is as follows:

"Use strict ";


Note: The browser of the old version treats it as a regular string and ignores it.

Iii. Declaring the location and context of the strict mode

Strict mode mainly affects the scope of a function, it does not change global scope and other unused functions into strict mode ). That is to say, the scope of the strict mode Declaration depends on its context. If the strict mode is declared in the Global Context (outside the scope of the function), all code in the program is in the strict mode. If the strict mode is declared in the function, all code in the function is in the strict mode. For example, in the following example, all the code is in strict mode, and the variable declaration outside the function may cause a syntax error: "undefined variable in strict mode "." Strict mode "has two calling methods, which are suitable for different scenarios.

1. For the entire script file

Place "use strict" in the first line of the script file, and the entire script runs in "strict mode. If this line of statements is not in the first line, it is invalid. The entire script runs in "normal mode. If code files in different modes are merged into one file, pay special attention to this.
(Strictly speaking, as long as the preceding statement does not produce the actual running result, "use strict" may not be in the first line, for example, directly following an empty Semicolon .)

The Code is as follows:


Script
"Use strict ";
Console. log ("this is the strict mode. ");
Script

Script
Console. log ("this is normal mode. ");
Script

The code above indicates that a webpage contains two Javascript codes in sequence. The tag of the previous script is in strict mode, and the tag of the last script is not.

2. For a single function

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

The Code is as follows:


Function strict (){
"Use strict ";
Return "this is the strict mode. ";
}
Function notStrict (){
Return "this is the normal mode. ";
}



3. Flexible script file writing

Because the first method is not conducive to file merging, it is better to use the second method to place the entire script file in an anonymous function that is executed immediately.

The Code is as follows:


(Function (){

"Use strict ";
// Some code here

})();

Iv. syntax and behavior changes in strict mode

Strict mode changes the syntax and behavior of Javascript.

1. explicit declaration of global variables

In normal Mode, when using variables, we do not have to declare (explicitly declare) with var, but in Strict Mode, variables must be declared with var before they can be used. Otherwise, an error occurs.

The Code is as follows:


"Use strict ";
V = 1; // error reported; v is not declared
For (I = 0; I <2; I ++) {// error, I is not declared
}


Therefore, in strict mode, variables must be declared with the var command before use.

2. Static binding

One feature of Javascript is to allow "dynamic binding", that is, the object to which certain attributes and Methods belong, not determined during compilation, but at runtime) OK.

The strict mode imposes some limitations on dynamic binding. In some cases, only static binding is allowed. That is to say, the object to which the attribute and method belong is determined at the compilation stage. This will help improve compilation efficiency and make the code easier to read and avoid accidents.

Specifically, it involves the following aspects.

(1) forbidden to use the with statement

The with statement cannot determine the object to which the attribute belongs during compilation.

The Code is as follows:


"Use strict ";
Var v = 1;
With (o) {// syntax error
V = 2;
}


(2) create eval Scope

In normal mode, Javascript has two variable scopes: global scope and function scope. Strict mode creates the third scope: eval scope.
In normal mode, the scope of an eval statement depends on whether it is in the global scope or function scope. In strict mode, the eval statement itself is a scope and can no longer generate global variables. The variables generated by the eval statement can only be used inside eval.

The Code is 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 this keyword from pointing to a Global Object

The Code is as follows:


Function f (){
Return! This;
}
// False is returned because "this" points to a global object ,"! This "is false
Function f (){
"Use strict ";
Return! This;
}


// Return true, because the value of this in strict mode is undefined, so "! This "is true.
Therefore, if you forget to add new when using the constructor, this will not point to the global object, but will report an error.

The Code is as follows:


Function f (){

"Use strict ";
This. a = 1;
};
F (); // error, this Is Not Defined


In a normal 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 a function is called through call and apply, if the input thisvalue parameter is a null or undefined Original Value (string, number, Boolean value ), the value of this will be the packaging object corresponding to the 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 conversion.

(2) do not traverse the call stack within the function.

The Code is as follows:


Function f1 (){

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

4. Disable the deletion of Variables

Variables cannot be deleted in strict mode. Only the property of an object whose retriable is set to true can be deleted.

The Code is as follows:


"Use strict ";
Var x;
Delete x; // syntax error
Var o = Object. create (null, 'x ',{
Value: 1,
Retriable: true
});
Delete o. x; // deletion successful

5. explicit error

In normal mode, a value is assigned to the read-only attribute of an object, and no error is reported. It only fails silently. In strict mode, an error is reported.

The Code is as follows:


"Use strict ";
Var o = {};
Object. defineProperty (o, "v", {value: 1, writable: false });
O. v = 2; // Error


In strict mode, if you assign a value to an attribute read using the getter method, an error is returned.

The Code is as follows:


"Use strict ";
Var o = {
Get v () {return 1 ;}
};
O. v = 2; // Error


In strict mode, an error is returned when a new attribute is added to an object that is not extended.

The Code is as follows:


"Use strict ";
Var o = {};
Object. preventExtensions (o );
O. v = 1; // Error


If you delete an attribute that cannot be deleted in strict mode, an error is returned.

The Code is as follows:


"Use strict ";
Delete Object. prototype; // Error

6. Duplicate name Error

Some syntax errors are added in strict mode.

(1) The object cannot have attributes with duplicate names.

In normal mode, if an object has multiple attributes with duplicate names, the attribute assigned at the end will overwrite the previous value. In strict mode, this is a syntax error.

The Code is as follows:


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

(2) The function cannot have parameters with duplicate names.

In normal mode, if the function has multiple cognominal parameters, you can use arguments [I] to read them. In strict mode, this is a syntax error.

The Code is as follows:


"Use strict ";
Function f (a, a, B) {// syntax error
Return;
}

7. Disable octal notation

In normal mode, if the first integer is 0, it indicates the octal number, for example, 0100 equals to 64 in decimal format. This notation is not allowed in strict mode. If the first integer is 0, an error is returned.

The Code is as follows:


"Use strict ";
Var n = 0100; // syntax error
8. Restrictions on arguments objects

Arguments is a parameter object of a function. Its use is strictly restricted by the mode.

(1) assigning values to arguments is not allowed.

The Code 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 Parameter Changes

The Code is as follows:


Function f (){
A = 2;
Return [a, arguments [0];
}
F (1); // The normal mode is [2, 2]
Function f (){
"Use strict ";
A = 2;
Return [a, arguments [0];
}
F (1); // The strict mode is [2, 1]


(3) Disable arguments. callee.

This means that you cannot call yourself within an anonymous function.

The Code is as follows:


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

9. The function must be declared on the top layer.

In the future, new Javascript versions will introduce block-level scopes ". To comply with the new version, the strict mode only allows you to declare a function at the top level of the global scope or function scope. That is to say, you cannot declare a function in a non-function code block.

The Code is as follows:


"Use strict ";
If (true ){
Function f () {}// syntax error
}
For (var I = 0; I <5; I ++ ){
Function f2 () {}// syntax error
}



10. Reserved Words

To transition to a new version of Javascript, some reserved words are added in strict mode: implements, interface, let, package, private, protected, public, static, and yield.
If you use these words as variables, an error is reported.

The Code is as follows:


Function package (protected) {// syntax error
"Use strict ";
Var implements; // syntax error
}


In addition, the fifth edition of ECMAscript also specifies other reserved words (class, enum, export, extends, import, super), and the const reserved words added by various browsers, it cannot be used as the variable name.
Related Article

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.