Understanding: iN addition to the normal mode provided by JavaScript, ES5 uses strict mode with restrictions after that.

  • In layman’s terms: run JS code under strict conditions
  • Compatibility: Internet Explorer 10 or above will only be supported, older browsers will be ignored.
  • Strict mode changes: figure

– Enable strict mode: Enable strict mode in the entire script or in a function

  • The entire script turns on strict mode: as shown below

  • Turn on strict mode in a function: as shown below

  • Strict mode changes:

1. Variable provisions

(1) Variables must be declared by var before they can be used

 num =10; printconsole.log(num); No command first in strict modevarThe correct statementCopy the code

(2) Do not delete declared variables at will

deletenum ; Delete num Do not delete declared variables in strict modeCopy the code

2. This refers to change

Normal mode: Normal functions in global scopethisPoint to thewindowStrict mode: Generic functions in global scopethisPoint to theundefined

Copy the code
  1. If the constructor is not called new,this will return an error:
 function Fu(){
  this.name ='li'; Error because herethisPoint to theundefined} Fu();} Fu()newNote: TimerthisOr towindowNote: The event object still points to the callerCopy the code

4. Function changes

(1) The same name cannot be used as a parameter

Different modes:function fn(a,a){
  console.log(a + a);
 }
 fn(1.2); The output4Strict mode:"use strict"
 function fn(a,a){
  console.log(a + a);
 }
 fn(1.2); Error: The same name of a parameter cannot be reportedCopy the code

(2) If and for cannot be put into a function, otherwise error

Strict mode:"use strict"
  if(true) {function fn(){}// A syntax error was reported
  }
 for(let i = 0; i <5 ; i ++){
   function fn(){}// A syntax error was reported} you can put functions inside functionsfunction fn(){ 
   function main(){}/ / legal
  } 
Copy the code

Conclusion:

  • Variable specifications :(1) the variable defined by ver (2) should not be deleted at will
  • This refers to :(1) the generic function of the global scope refers to undefined (2) the constructor without new refers to undefined
  • Function changes: (1) parameter names cannot have the same name (2) functions cannot be defined in if and for
  • More strict mode for reference: developer.mozilla.org/zh-CN/docs/…