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

前端 未结 28 3090
半阙折子戏
半阙折子戏 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

    "use strict" makes JavaScript code to run in strict mode, which basically means everything needs to be defined before use. The main reason for using strict mode is to avoid accidental global uses of undefined methods.

    Also in strict mode, things run faster, some warnings or silent warnings throw fatal errors, it's better to always use it to make a neater code.

    "use strict" is widely needed to be used in ECMA5, in ECMA6 it's part of JavaScript by default, so it doesn't need to be added if you're using ES6.

    Look at these statements and examples from MDN:

    The "use strict" Directive
    The "use strict" directive is new in JavaScript 1.8.5 (ECMAScript version 5). It is not a statement, but a literal expression, ignored by earlier versions of JavaScript. The purpose of "use strict" is to indicate that the code should be executed in "strict mode". With strict mode, you can not, for example, use undeclared variables.

    Examples of using "use strict":
    Strict mode for functions: Likewise, to invoke strict mode for a function, put the exact statement "use strict"; (or 'use strict';) in the function's body before any other statements.

    1) strict mode in functions

     function strict() {
         // Function-level strict mode syntax
         'use strict';
         function nested() { return 'And so am I!'; }
         return "Hi!  I'm a strict mode function!  " + nested();
     }
     function notStrict() { return "I'm not strict."; }
    
     console.log(strict(), notStrict());
    

    2) whole-script strict mode

    'use strict';
    var v = "Hi! I'm a strict mode script!";
    console.log(v);
    

    3) Assignment to a non-writable global

    'use strict';
    
    // Assignment to a non-writable global
    var undefined = 5; // throws a TypeError
    var Infinity = 5; // throws a TypeError
    
    // Assignment to a non-writable property
    var obj1 = {};
    Object.defineProperty(obj1, 'x', { value: 42, writable: false });
    obj1.x = 9; // throws a TypeError
    
    // Assignment to a getter-only property
    var obj2 = { get x() { return 17; } };
    obj2.x = 5; // throws a TypeError
    
    // Assignment to a new property on a non-extensible object.
    var fixed = {};
    Object.preventExtensions(fixed);
    fixed.newProp = 'ohai'; // throws a TypeError
    

    You can read more on MDN.

提交回复
热议问题