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

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

    JavaScript “strict” mode was introduced in ECMAScript 5.

    (function() {
      "use strict";
      your code...
    })();
    

    Writing "use strict"; at the very top of your JS file turns on strict syntax checking. It does the following tasks for us:

    1. shows an error if you try to assign to an undeclared variable

    2. stops you from overwriting key JS system libraries

    3. forbids some unsafe or error-prone language features

    use strict also works inside of individual functions. It is always a better practice to include use strict in your code.

    Browser compatibility issue: The "use" directives are meant to be backwards-compatible. Browsers that do not support them will just see a string literal that isn't referenced further. So, they will pass over it and move on.

提交回复
热议问题