JavaScript Strict mode

Source: Internet
Author: User

E Cmascript 5 first introduced the concept of "strict mode" (strict). With strict mode, you can get inside the function

Select to perform a more rigorous global or local error condition detection. The advantage of using strict mode is that you can know the code in advance

Errors and capture some of the ECMAScript behaviors that can lead to programming errors in time.

It is important to understand the rules of strict patterns, and the next version of ECMAScript will be based on a rigorous model. Support for Strict mode

-style browsers include ie10+, Firefox 4+, Safari 5.1+, and Chrome.

1. Select Use

To opt into strict mode, you can use strict mode compilation instructions (pragma), which is actually one that will not be assigned to any variable

Amount of String:

"Use strict";

This syntax (supported from ECMAScript 3) can be backwards compatible with JavaScript engines that do not support strict mode. Support

The strict mode engine starts this mode, and the engine that does not support the pattern encounters an unassigned string literal and then

This compiles the instructions slightly.

If this compilation instruction is given in the global scope (outside the function), the entire script will use strict mode. Other words

If you put a script with this compilation instruction in another file, the JavaScript code in that file will also be in strict mode.

You can also just turn on strict mode in the function, just like this:

function dosomething () {"use strict"; // other Code }

If you do not have the power to control all the scripts in the page, it is recommended that you only turn on strict mode in the specific function that you want to test.

2. Variables

In strict mode, there is a limit as to when to create variables and how to create them. First, you are not allowed to accidentally create a global change

Amount In non-strict mode, you can create a global variable as follows:

// variable not declared // non-strict mode: Create global variables // Strict mode: throws referenceerrormessage = "Hello world!";

Even if there is no var keyword in front of the message, even if it is not defined as a property of a global object, the message can be

Created as a global variable. In strict mode, however, if you assign a value to a variable that is not declared, the code will be thrown when it executes.

Referenceerror.

Second, you cannot call the delete operator on a variable. Non-strict mode allows such operations, but silently fails (returns false).

In strict mode, deleting a variable also results in an error.

// Delete a variable // non-strict mode: Silent failure // Strict mode: Throw Referenceerror var color = "Red"; delete color;

There are also restrictions on variable names in strict mode. In particular, you cannot use implements, interface, let,

Private, protected, public, static, and yield as variable names. These are reserved words, the future of ECMAScript

They may be used in the version. In strict mode, using the above identifier as the variable name results in a syntax error.

3. Objects

Manipulating objects in strict mode is more likely to cause errors than in non-strict mode. In general, non-strict mode will silently fail
Case, an error is thrown in strict mode. Therefore, using strict patterns in development increases the likelihood of early detection of errors.
Manipulating the properties of an object causes an error in the following situations:
? Assigning a value to a read-only property throws a typeerror;
? Using the delete operator on a non-configurable (nonconfigurable) property throws TypeError;
? Adding a property to an object that is not extensible (nonextensible) throws TypeError.
Another restriction on using objects is related to declaring objects by object literals. Property names must be unique when using object literals.
For example:

// Duplicate name attribute // non-strict mode: No error, whichever is the second attribute // Strict mode: throws a syntax error var person ="Nicholas""Greg"};

The object person here has two attributes, called name. In non-strict mode, the Name property value of the person object is the first
Two, and in strict mode, such code can cause syntax errors.

4. Functions

First, strict mode requires that the parameters of a named function must be unique. Take the following function as an example:

// Duplicate Parameter // non-strict mode: no error, only the second parameter can be accessed // Strict mode: throws a syntax error function sum (num, num) {//dosomething}

In non-strict mode, this function declaration does not throw an error. Only the second parameter can be accessed through the parameter name, to access the first parameter

The number must pass through the arguments object.

In strict mode, the behavior of the arguments object is also different. In non-strict mode, modifying the value of a named parameter also counter-

To the arguments object, and the two values are completely independent in strict mode. For example:

// Modifying the value of a named parameter // non-strict mode: changes are reflected in the arguments // Strict mode: Modifications are not reflected in the arguments function  = "foo"//"foo"// non-strict mode: "foo"// Strict mode: " Hi "}showvalue" ("HI");

In the above code, the function Showvalue () has only one named parameter, value. When this function is called, a parameter "Hi" is passed in.

This value is assigned to value. Inside the function, value is changed to "Foo". In non-strict mode, this change also changes

Arguments[0] value, but in strict mode, the value of arguments[0] is still the value passed in.

Another change is the elimination of Arguments.callee and Arguments.caller. In non-strict mode, these two genera

A reference function itself, a reference calling function. In strict mode, which property is accessed will throw typeerror.

For example:

// Visit Arguments.callee // non-strict mode: no problem // Strict mode: Throw TypeError function factorial (num) {if (num <= 1) {return 1else  {  return num * Arguments.callee (num-1)}}var result=factorial (5);

Similarly, attempting to read and write the caller property of a function also causes the TypeError to be thrown. So, for the above example,

Access to Factorial.caller also throws an error.

Similar to variables, strict mode limits the function name and does not allow implements, interface, let, package,

Private, protected, public, static, and yield as function names.

The last point of the function is to declare functions only at the top level of the script and inside the function. In other words, in the IF statement

Declaring a function causes a syntax error:

// declaring a function in an if statement // non-strict mode: Promote a function outside the IF statement // Strict mode: throws a syntax error if (true) {function  dosomething () {//... }}

In non-strict mode, the above code can be run in all browsers, but in strict mode it causes a syntax error.

5.eval ()

The criticized Eval () function has also been promoted in strict mode. The biggest change is that it is no longer created in the inclusion context

Variable or function. For example:

// Create a variable using eval () // non-strict mode: Pop-up dialog box displays // Strict mode: Referenceerror is thrown when alert (x) is called function dosomething () {eval("var x=10"); alert (x);}

In the case of non-strict mode, the above code creates a local variable x in the function dosomething () and then the alert ()

The value of the variable is also displayed. In strict mode, however, calling Eval () in the dosomething () function does not create a variable x, so

Calling alert () causes the Referenceerror to be thrown because x is not defined.

Variables and functions can be declared in eval (), but these variables or functions are valid only in the particular scope of the evaluation, and then

will be destroyed. Therefore, the following code can be run without a problem:

"Use strict"; var result = eval ("var x=10, y=11; X+y "//

The variables x and Y are declared here in eval (), and then they are added together to return their and. Thus, the result changes

The value of the amount is 21, which is the result of the addition of x and Y. When alert () is called, even though X and y no longer exist, the result variable

The value is still valid.

6.eval and arguments

Strict mode has explicitly forbidden the use of eval and arguments as identifiers, nor does it allow reading and writing of their values. For example:

// use eval and arguments as variable references // non-strict mode: No problem, no error // Strict mode: throws a syntax error var eval = ten; var arguments = "Hello world!";

In non-strict mode, you can override eval or assign a value to arguments. However, in strict mode, doing so will result in the language

Error in the method. They cannot be used as identifiers, which means that syntax errors are thrown in the following ways:

? use VAR declaration;

? give another value;

? Try to modify the included values, such as using + +;

? Used as the name of a function;

? Used as a named function parameter;

? Used as the exception name in the Try-catch statement.

7. Suppress this

One of the biggest security problems in JavaScript is the most confusing, and in some cases how to suppress this

The value. When using the Apply () or call () method of a function in non-strict mode, null or undefined values are converted to global

Object. In strict mode, the this value of the function is always the specified value, regardless of the value specified. For example:

// Accessing Properties // non-strict mode: Access Global Properties // Strict mode: throws an error because the value of this is null var color = "Red"; function Displaycolor () {alert (this. color);} Displaycolor.call (null);

The above code passed null to Displaycolor.call (), if in non-strict mode, this means that the function's this

The value is a global object. The result is a popup dialog showing "Red". In strict mode, the value of this function is null, because

This throws an error when accessing a null property.

8. Other changes

There are some other changes in the strict mode, which I hope readers can pay attention to. The first is to discard the WITH statement. With in non-strict mode

The statement can change the path of the parsing identifier, but in strict mode, with is simplified. Therefore, using the with in strict mode

can cause a syntax error.

// Statement usage with // non-strict mode: Allow // Strict mode: throws a syntax error  with (location) {alert (href);}

Strict mode also removes the octal literal in JavaScript. Octal literals, beginning with 0, often lead to many mistakes in the past.

Miss. In strict mode, the octal literal has become an invalid syntax.

// using octal literals // non-strict mode: A value of 8 // Strict mode: throws a syntax error var value = 010;

ECMAScript 5 also modifies the behavior of parseint () in strict mode. Today, the eight-step literal is

Strict mode is treated as a decimal literal that begins with 0. For example:

// parsing octal literals using parseint () // non-strict mode: A value of 8 // Strict mode: value is ten var value = parseint ("010");

JavaScript Strict mode

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.