Detailed Explanation of JavaScript Strict Mode

  • 2021-07-12 04:24:00
  • OfStack

1. Overview

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

The main purposes of setting up the "strict model" are as follows:

a-Eliminate some unreasonable and imprecise parts of Javascript grammar and reduce some strange behaviors;

b-Eliminate some insecurity of code running, ensure the safety of code running;

c-Improve compiler efficiency and increase running speed;

d-paves the way for the new version of Javascript in the future.

The "strict mode" reflects the more reasonable, safer and more rigorous development direction of Javascript. Mainstream browsers including IE 10 have already supported it, and many large projects have begun to embrace it in an all-round way.

On the other hand, the same code, in "strict mode", may have different running results; 1 Statements that can run in "normal mode" will not run in "strict mode". Mastering these contents will help you understand Javascript more carefully and deeply, and make you a better programmer.

2. Entry sign

The sign of entering the "strict mode" is:

“use strict”;

3. How to call

"Strict Mode" has two invocation methods, which are suitable for different occasions.

3.1 For the entire script file

Put "use strict" on line 1 of the script file, and the entire script will run in "strict mode." If this line statement is not in line 1, it is invalid and the whole script runs in "normal mode". If the code files of different modes are merged into one file, this one point needs special attention.

(Strictly speaking, "use strict" may not be in line 1, such as directly following an empty semicolon, as long as it is not preceded by a statement that produces the actual running result. )


      <script>
            "use strict";
            console.log(" This is the 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 has about 50 computers.
      </script>

The above code shows that there are two Javascript codes in one web page in turn. The first script tag is in strict mode, and the last one is not.

3.2 For a single function

Put "use strict" in line 1 of the function body, and the whole function runs in "strict mode."


      function strict(){
            "use strict";
            return " This is the strict mode. ";
      }
      function notStrict() {
            return " This is normal mode. ";
      }

3.3 Alternative Writing of Script Files

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


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

4. Grammar and behavior changes

Strict mode has made some changes to the syntax and behavior of Javascript.

4.1 Explicit Declaration of Global Variables

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


  "use strict";
      v = 1; //  Report an error, v Undeclared 
      for(i = 0; i < 2; i++) { //  Report an error, i Undeclared 
      }

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

4.2 Static binding

One feature of Javascript language is that it allows "dynamic binding", that is, which object certain attributes and methods belong to, is determined not at compile time, but at runtime (runtime).

Strict mode imposes some restrictions on dynamic binding. In some cases, only static bindings are allowed. That is to say, the object to which the attributes and methods belong is determined at the compilation stage. Doing so is beneficial to improve compilation efficiency, and also makes the code easier to read and less unexpected.

Specifically, it involves the following aspects.

(1) Prohibit the use of with statements

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


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

(2) Create eval scope

In normal mode, the Javascript language has two variable scopes (scope): global scope and function scope. Strict mode creates a third scope: eval scope.

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


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

4.3 Enhanced security measures

(1) Disable this keywords from pointing to global objects


      function f(){
            return !this;
      }
      //  Return false , because "this" Point to a global object, "!this" Is false
      function f(){
            "use strict";
            return !this;
      }
      //  Return true Because in strict mode, this The value of is undefined , so "!this" For true

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


      function f(){
            "use strict";
            this.a = 1;
      };
      f();//  Report an error, this Undefined 

(2) It is forbidden to traverse the call stack inside the function


      function f1(){
            "use strict";
            f1.caller; //  Report an error 
            f1.arguments; //  Report an error 
      }
      f1();

4.4 Disable Deleting Variables

Variables cannot be deleted in strict mode. Only objects whose configurable is 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 reporting

In normal mode, assigning a read-only attribute to an object will not report an error, but will only fail silently. In strict mode, an error will be reported.


      function strict(){
            "use strict";
            return " This is the strict mode. ";
      }
      function notStrict() {
            return " This is normal mode. ";
      }
0

In strict mode, an error will be reported if you assign a value to an attribute read by getter method.


      function strict(){
            "use strict";
            return " This is the strict mode. ";
      }
      function notStrict() {
            return " This is normal mode. ";
      }
1

In strict mode, adding new attributes to objects that are prohibited from being extended will report an error.


      function strict(){
            "use strict";
            return " This is the strict mode. ";
      }
      function notStrict() {
            return " This is normal mode. ";
      }
2

In strict mode, deleting an attribute that cannot be deleted will report an error.


      "use strict";
      delete Object.prototype; //  Report an error 

4.6 Duplicate name error

Strict mode adds 1 syntax error.

(1) Objects cannot have properties with duplicate names

In normal mode, if an object has more than one property with the same name, the last property assigned overrides the previous value. In strict mode, this is a grammatical error.


      function strict(){
            "use strict";
            return " This is the strict mode. ";
      }
      function notStrict() {
            return " This is normal mode. ";
      }
4

(2) Function cannot have arguments with duplicate names

In normal mode, if a function has multiple arguments with the same name, it can be read using arguments [i]. In strict mode, this is a grammatical error.


      function strict(){
            "use strict";
            return " This is the strict mode. ";
      }
      function notStrict() {
            return " This is normal mode. ";
      }
5

4.7 Prohibiting Octal Notation

In normal mode, if the first bit of an integer is 0, it means that it is an octal number, for example, 0100 equals 64 in decimal. Strict mode prohibits this notation. If the first bit of the integer is 0, an error will be reported.


      function strict(){
            "use strict";
            return " This is the strict mode. ";
      }
      function notStrict() {
            return " This is normal mode. ";
      }
6

4.8 Limitations of arguments Objects

arguments is a parameter object of a function, and its use is limited by strict schema.

(1) Assignment to arguments is not allowed


      function strict(){
            "use strict";
            return " This is the strict mode. ";
      }
      function notStrict() {
            return " This is normal mode. ";
      }
7

(2) arguments no longer tracks parameter changes


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


      function strict(){
            "use strict";
            return " This is the strict mode. ";
      }
      function notStrict() {
            return " This is normal mode. ";
      }
9

4.9 Functions must be declared at the top level

The new version of Javascript will introduce "block-level scope" in the future. To keep up with the new version, Strict Mode only allows functions to be declared at the top level of global scope or function scope. That is, it is not allowed to declare a function within a code block that is not a function. (This is Mr. Ruan's note in 2013, and now ES6 has introduced block-level scope)


      "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 the new version of Javascript in the future, one reserved word has been added to the strict mode: implements, interface, let, package, private, protected, public, static and yield.

Using these words as variable names will report errors.


      function package(protected) { //  Syntax error 
            "use strict";
            var implements; //  Syntax error 
      }

In addition, the 5th edition of ECMAscript itself also stipulates another reserved word (class, enum, export, extends, import, super), and the reserved word const added by major browsers themselves cannot be used as variable names.


Related articles: