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

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

    Small examples to compare:

    Non-strict mode:

    for (i of [1,2,3]) console.log(i)
        
    // output:
    // 1
    // 2
    // 3

    Strict mode:

    'use strict';
    for (i of [1,2,3]) console.log(i)
    
    // output:
    // Uncaught ReferenceError: i is not defined

    Non-strict mode:

    String.prototype.test = function () {
      console.log(typeof this === 'string');
    };
    
    'a'.test();
    
    // output
    // false

    String.prototype.test = function () {
      'use strict';
      
      console.log(typeof this === 'string');
    };
    
    'a'.test();
    
    // output
    // true

提交回复
热议问题