Javascript Strict Mode detailed

Source: Internet
Author: User
Tags script tag

Note: This article is reproduced in the article reprinted address: http://www.ruanyifeng.com/blog/2013/01/javascript_strict_mode.html

I. Overview

In addition to the normal operating mode, ECMAscript 5 adds a second mode of operation: "Strict mode" (strict). As the name implies, this mode allows JavaScript to run under stricter conditions.

The purpose of setting up a "strict mode" is mainly as follows:

-Eliminate some of the unreasonable and less rigorous JavaScript syntax, and reduce some of the bizarre behavior;

-Eliminate some of the unsafe code operation, to ensure the security of code operation;

-Improve the efficiency of the compiler, increase the speed of operation;

-Pave the future for new versions of JavaScript.

"Strict mode" embodies JavaScript more reasonable, more secure, more rigorous development direction, including IE 10 mainstream browser, has supported it, many large projects have begun to embrace it fully.

On the other hand, the same code, in "Strict mode", may have different running results; some statements that can be run under normal mode will not work in strict mode. Mastering these elements will help you understand JavaScript more carefully and make you a better programmer.

This article will introduce the "strict mode" in detail.

Ii. Signs of entry

Enter the "strict mode" flag, which is the following line of statements:

"Use strict";

Older browsers will ignore it as a single line of normal strings.

Third, how to call

There are two methods of calling strict mode, which are suitable for different situations.

3.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 the line statement is not in the first row, it is not valid and the entire script runs in normal mode. This requires special attention if the code files of different schemas are merged into one file.

(Strictly speaking, "use strict" may not be in the first line, as long as the previous statement does not produce the actual result of the operation, such as directly following an empty semicolon.) )

<script>
"Use strict";
Console.log ("This is strict mode. ");
</script>

<script>
Console.log ("This is normal mode.) "); kly, it ' s almost 2 years ago now. I can admit it now-i run it on my school's network that have about the computers.
</script>

The code above indicates that there are two snippets of JavaScript code in one page. The previous script tag is strict mode, and the latter one is not.

3.2 for a single function

When use strict is placed in the first row of the function body, the entire function runs in strict mode.

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

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

3.3 Workarounds for script files

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

(function () {

"Use strict";

Some code here

})();

Iv. Grammatical and behavioral changes

Strict mode has made some changes to JavaScript's syntax and behavior.

4.1 Explicit declaration of global variables

In normal mode, if a variable is assigned without a declaration, the default is the global variable. Strict mode prohibits this usage, and global variables must be explicitly declared.

"Use strict";

v = 1; Error, v not declared

for (i = 0; i < 2; i++) {//error, I not stated
}

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

4.2 Static bindings

One feature of the JavaScript language is that it allows "dynamic binding", that is, which object the properties and methods belong to, not determined at compile time, but at runtime.

Strict mode has some restrictions on dynamic binding. In some cases, only static bindings are allowed. That is, the property and method belong to which object, which is determined at the compile stage. This facilitates compilation efficiency and makes the code easier to read and less unexpected.

Specifically, the following areas are involved.

(1) Prohibit the use of with statements

Because the WITH statement cannot be determined at compile time, the property exactly belongs to which object.

"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. Strict mode creates a third scope: the scope of the eval.

In normal mode, the scope of the Eval statement depends on whether it is in the global scope or at the function scope. In strict mode, the Eval statement itself is a scope that can no longer generate global variables, and it generates variables that can only be used inside the eval.

"Use strict";

var x = 2;

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

Console.info (x); 2

4.3 Enhanced security

(1) Prohibit the This keyword from pointing to global objects

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 the value of this is undefined in strict mode, so "!this" is true.

Therefore, when using the constructor, if you forget to add new,this no longer point to the global object, but instead error.

function f () {

"Use strict";

THIS.A = 1;

};

f ();//error, this is undefined

(2) Prohibit traversal of the call stack inside a function

Function F1 () {

"Use strict";

F1.caller; Error

f1.arguments; Error

}

F1 ();

4.4 Disable deletion of variables

The variable cannot be deleted in strict mode. Only configurable object properties that are set to True can be deleted.

"Use strict";

var x;

Delete x; Syntax error

var o = object.create (null, {' x '): {
Value:1,
Configurable:true
}});

Delete o.x; Delete Succeeded

4.5 Explicit error

In normal mode, the read-only property of an object is assigned, no error is made, and only silently fails. Strict mode, will be an error.

"Use strict";

var o = {};

Object.defineproperty (O, "V", {value:1, writable:false});

O.V = 2; Error

In strict mode, a property that is read using the Getter method is assigned an error.

"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 extended will cause an error.

"Use strict";

var o = {};

Object.preventextensions (o);

O.V = 1; Error

Strict mode, delete a non-deleted property, will be an error.

"Use strict";

Delete Object.prototype; Error

4.6 Duplicate Name Errors

Some syntax errors have been added to strict mode.

(1) An object cannot have a property with duplicate name

In normal mode, if the object has more than one duplicate attribute, the last assigned value overrides the previous value. In strict mode, this is a syntax error.

"Use strict";

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

(2) function cannot have parameter with duplicate name

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

"Use strict";

function f (A, A, b) {//Syntax error

return;

}

4.7 Prohibition of octal notation

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

"Use strict";

var n = 0100; Syntax error

4.8 Limitations of Arguments objects

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

(1) Arguments assignment is not allowed

"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 changes in parameters

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 call yourself inside an anonymous function.

"Use strict";

var f = function () {return arguments.callee;};

f (); Error

4.9 functions must be declared at the top level

A new version of JavaScript will introduce a "block-level scope" in the future. In order to conform to 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 a function within a block of code that is not a function.

"Use strict";

if (true) {

function f () {}//Syntax error

}

for (var i = 0; i < 5; i++) {

function F2 () {}//Syntax error

}

4.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 variable names will cause an error.

function package (Protected) {//Syntax error

"Use strict";

var implements; Syntax error

}

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

V. Reference links

-MDN, Strict mode
-Dr. Axel Rauschmayer,javascript ' s strict mode:a summary
-Douglas Crockford, Strict Mode is Coming

Finish

Javascript Strict Mode detailed

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.