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

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

    If people are worried about using use strict it might be worth checking out this article:

    ECMAScript 5 'Strict mode' support in browsers. What does this mean?
    NovoGeek.com - Krishna's weblog

    It talks about browser support, but more importantly how to deal with it safely:

    function isStrictMode(){
        return !this;
    } 
    /*
       returns false, since 'this' refers to global object and 
       '!this' becomes false
    */
    
    function isStrictMode(){   
        "use strict";
        return !this;
    } 
    /* 
       returns true, since in strict mode the keyword 'this'
       does not refer to global object, unlike traditional JS. 
       So here, 'this' is 'undefined' and '!this' becomes true.
    */
    

提交回复
热议问题