What does “use strict” do in JavaScript, and what is the reasoning behind it?

前端 未结 28 3077
半阙折子戏
半阙折子戏 2020-11-21 06:05

Recently, I ran some of my JavaScript code through Crockford\'s JSLint, and it gave the following error:

Problem at line 1 character 1: Missing \"use

28条回答
  •  臣服心动
    2020-11-21 06:52

    When adding "use strict";, the following cases will throw a SyntaxError before the script is executing:

    • Paving the way for future ECMAScript versions, using one of the newly reserved keywords (in prevision for ECMAScript 6): implements, interface, let, package, private, protected, public, static, and yield.

    • Declaring function in blocks

      if(a
    • Octal syntax

      var n = 023;
      
    • this point to the global object.

       function f() {
            "use strict";
            this.a = 1;
       };
       f(); 
      
    • Declaring twice the same name for a property name in an object literal

       {a: 1, b: 3, a: 7} 
      

      This is no longer the case in ECMAScript 6 (bug 1041128).

    • Declaring two function arguments with the same name function

      f(a, b, b){}
      
    • Setting a value to an undeclared variable

      function f(x){
         "use strict";
         var a = 12;
         b = a + x*35; // error!
      }
      f();
      
    • Using delete on a variable name delete myVariable;

    • Using eval or arguments as variable or function argument name

      "use strict";
      arguments++;
      var obj = { set p(arguments) { } };
      try { } catch (arguments) { }
      function arguments() { } 
      

    Sources:

    • Transitioning to strict mode on MDN

    • Strict mode on MDN

    • JavaScript’s Strict Mode and Why You Should Use It on Colin J. Ihrig's blog (archived version)

提交回复
热议问题