js strict mode

I. Overview

In addition to the normal mode of operation, ECMAscript 5 adds a second mode of operation: "strict mode" . As the name suggests, this mode makes Javascript run under stricter conditions.

The purpose of establishing "strict mode" is mainly as follows:

  - Eliminate some unreasonable and imprecise aspects of Javascript syntax and reduce some weird behaviors;

  - Eliminate some insecurities of code operation and ensure the safety of code operation;

  - Improve compiler efficiency and increase running speed;

  - To 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 already supported it, and many large projects have begun to fully embrace it.

On the other hand, the same code may run differently in "strict mode"; some statements that can run in "normal mode" will not run in "strict mode". Mastering these content will help you understand Javascript in more detail and make you a better programmer.

This article will introduce "strict mode" in detail.

2. Entry sign

The sign to enter "strict mode" is the following line:

  "use strict";

Older browsers treat it as a normal string and ignore it.

3. How to call

"Strict mode" has two methods of invocation, suitable for different occasions.

3.1 For the entire script file

Put "use strict" on the first line of your script file and the entire script will run in "strict mode". If this line of statements is not on the first line, it is invalid and the entire script runs in "normal mode". This requires special attention if code files of different modes are merged into one file.

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

  <script>
    "use strict";
    console.log("This is strict mode.");
  </script>

  <script>
    console.log("这是正常模式。");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 indicates that there are two pieces of Javascript code in a web page in turn. The former script tag is strict mode, the latter is not.

3.2 For a single function

Put "use strict" on the first line of the function body, and 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 Alternative writing of script files

Because the first method of calling 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

   })();

4. Grammatical and behavioral changes

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

4.1 Explicit declaration of global variables

In normal mode, if a variable is assigned a value without a declaration, it defaults to a global variable. Strict mode prohibits this usage, global variables must be declared explicitly.

"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 they are used.

4.2 Static binding

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

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

Specifically, it involves the following aspects.

(1) Prohibit the use of the with statement

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

  "use strict";

  var v = 1;

  with (o){ // syntax error 
    v = 2;
  }

(2) Create an eval scope

In normal mode, the Javascript language has two variable scopes: the global scope and the function scope. Strict mode creates a third type of scope: the 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) The this keyword is prohibited from pointing to the global object

  function f(){
    return !this;
  } 
  // return false, because "this" points to the global object, "!this" is false

  function f(){ 
    "use strict";
    return !this;
  } 
  // Returns true, because in strict mode, the value of this is undefined, so "!this" is true.

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

  function f(){

    "use strict";

    this.a = 1;

  };

  f();// error, this is undefined

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

  function f1(){

    "use strict";

    f1.caller; // error

    f1.arguments; // error

  }

  f1 ();

4.4 Prohibit deletion of variables

Variables cannot be deleted in strict mode. Only object properties with configurable 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 ox; // delete successfully

4.5 Explicit error reporting

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

  "use strict";

  var o = {};

  Object.defineProperty(o, "v", { value: 1, writable: false });

  ov = 2; // report an error

In strict mode, assigning a value to a property read using the getter method will result in an error.

  "use strict";

  var o = {

    get v() { return 1; }

  };

  ov = 2; // report an error

In strict mode, adding a new property to an object whose extension is prohibited will result in an error.

  "use strict";

  var o = {};

  Object.preventExtensions(o);

  ov = 1; // report an error

In strict mode, deleting an undeletable property will result in an error.

  "use strict";

  delete Object.prototype; // error

4.6 Duplicate Name Error

Strict mode adds some syntax errors.

(1) Objects cannot have properties with the same name

In normal mode, if an object has multiple properties with the same name, the property assigned last 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 the same name

In normal mode, if a function has multiple parameters with the same name, they 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 Prohibit Octal Notation

In normal mode, if the first digit of an integer is 0, it means that this is an octal number, for example, 0100 is equal to 64 in decimal. Strict mode forbids this notation, and an integer with a 0 in the first digit will report an error.

  "use strict";

  var n = 0100; // syntax error

4.8 Limitations of the arguments object

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

(1) Assignment 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 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, you can't call itself inside an anonymous function.

  "use strict";

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

  f(); // error

4.9 Functions must be declared at the top level

Future versions of Javascript will introduce "block scopes". In keeping with newer versions, strict mode only allows functions to be declared at the top level of the global scope or function scope. That is, functions are not allowed to be declared inside code blocks that are not functions.

  "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 new versions 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 result in an error.

  function package(protected) { // syntax error

    "use strict";

    var implements; // syntax error

  }

In addition, the fifth version of ECMAscript also stipulates other reserved words (class, enum, export, extends, import, super), as well as const reserved words added by major browsers, which cannot be used as variable names.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324814562&siteId=291194637