Strict JavaScript mode explanation _ javascript skills

Source: Internet
Author: User
In the strict JavaScript mode, some restrictions are imposed on JavaScript writing. If these restrictions are violated in the strict mode, the code will report an error. If you are interested in the knowledge of the strict mode of javascript, learn it together. As we know, JavaScript is a flexible language. Its flexibility also brings about many pitfalls. Of course, there are also some design defects. For example

A value is assigned if a variable is not declared. The default value is a global variable, as shown in figure

(Function () {a = 3 ;}) (); console. log (window. a); // output 3

The object has multiple duplicate attributes. The attribute assigned at the end will overwrite the previous values. For example

Var obj = {c: 3, c: 4} // obj is {c: 4}

There are countless pitfalls such as =, typeof. After all, it took only a week for the father of JavaScript to design the language.

What is the strict JavaScript mode?

In the strict JavaScript mode, some restrictions are imposed on JavaScript writing. If these restrictions are violated in strict mode, the code will report an error.

I. Overview

In addition to the normal running mode, ECMAscript 5 adds the second running mode: strict mode ). As the name suggests, this mode allows Javascript to run under more stringent conditions.

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

-Eliminate unreasonable and not rigorous Javascript syntax and reduce some weird behavior;

-Eliminate some unsafe aspects of code running to ensure the security of code running;

-Improve compiler efficiency and speed;

-Pave the way 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. Entry mark

The mark for entering the "strict mode" is the following line of statements:

"Use strict ";

The browser of the old version ignores it as a regular string.

Iii. How to call

There are two calling methods for "strict mode", which are suitable for different scenarios.

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

Script "use strict"; console. log ("this is a strict mode. "); Script, script console. log (" this is the 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.

3.2 for a single function

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

Function strict () {"use strict"; return "this is a strict mode. ";} Function notStrict () {return" this is the normal mode. ";}

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

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

Iv. syntax and behavior changes

The strict mode changes the syntax and behavior of Javascript.

4.1 explicit declaration of global variables

In normal mode, if a variable is not declared, the value is assigned. The default value is global variable. This is not allowed in strict mode. The global variables must be explicitly declared.

"Use strict"; v = 1; // error, 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.

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

Dynamic binding is not allowed in strict mode, but static binding is allowed only. That is to say, the object to which the attribute and method belong must be 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.

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

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

4.3 enhanced security measures

(1) prohibit this keyword from pointing to a Global Object

Function f () {return! This;} // returns false because "this" points to a global object ,"! This "is falsefunction 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.

Function f () {"use strict"; this. a = 1 ;}; f (); // error, this Is Not Defined

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

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

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

"Use strict"; var x; delete x; // syntax error var o = Object. create (null, 'x', {value: 1, retriable: true}); delete o. x; // deletion successful

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

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

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

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

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

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

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

"Use strict"; function f (a, a, B) {// syntax error return ;}

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

"Use strict"; var n = 0100; // syntax error

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

"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

Function f (a) {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.

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

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

"Use strict"; if (true) {function f () {}// syntax error} for (var I = 0; I <5; I ++) {function f2 () {}// syntax error}

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

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, and super. They are also unavailable.

The above content is the full explanation of the strict JavaScript mode introduced by the editor. I hope you will like it.

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.