如何使用JSLint全局设置'use strict'

时间:2016-02-09 16:43:00

标签: javascript jslint use-strict

我是javascript的新手,正在尝试通过JSLint进行验证。 我应该在哪里使用“use strict”在全球范围内使用它并验证?

这给了我错误“在语句位置使用严格'的意外表达式。”:

    "use strict";
    console.log('doing js in head-section');

    function helloWorld() {
        console.log('called function helloWorld()');
        alert('Hello World from a JS function showing an alert!');
    }

    function helloMyNumber() {
        console.log('called function helloMyNumber()');
        var max = 42;
        var yourLuckyNumber = prompt('Enter your lucky number (between 1 and '+ max +')');
        var myLuckyNumber = Math.floor(Math.random()*(max+1));
        var paragraph = document.getElementById('luckynumber');
        paragraph.innerHTML = paragraph.innerHTML + ' Your lucky number is: ' + yourLuckyNumber + '. Mine is: ' + myLuckyNumber + '. They ' + (yourLuckyNumber == myLuckyNumber ? 'DID ' : 'did NOT ') + 'match!';
    }



    console.log('doing JS in body-section');
    document.writeln('<p class="green">Hello World from JS within a body-section in HTML!</p>');

2 个答案:

答案 0 :(得分:5)

根据the documentation,JSLint的browser选项会自动禁用全局级"use strict";的使用。据我所知,没有办法让它重新开启。

您可以使用以下命令关闭浏览器选项,并获取与browser选项相同的预先声明的全局变量:

/*global
Audio, clearInterval, clearTimeout, document, event, history, Image, location, name, navigator, Option, screen, setInterval, setTimeout, XMLHttpRequest
*/

或者,您可以将所有代码包装在IIFE中,并在其顶部使用"use strict";

或者,您可以切换到JSHint(有更多选项),并使用其strict: global选项在全局范围内允许"use strict";

答案 1 :(得分:1)

'use strict'通常用于函数的开头。对于你的代码,我只是将它全部包装在IIFE中,这将使'use strict'有效

(function() {
    "use strict";
    console.log('doing js in head-section');

    function helloWorld() {
        console.log('called function helloWorld()');
        alert('Hello World from a JS function showing an alert!');
    }

    function helloMyNumber() {
        console.log('called function helloMyNumber()');
        var max = 42;
        var yourLuckyNumber = prompt('Enter your lucky number (between 1 and '+ max +')');
        var myLuckyNumber = Math.floor(Math.random()*(max+1));
        var paragraph = document.getElementById('luckynumber');
        paragraph.innerHTML = paragraph.innerHTML + ' Your lucky number is: ' + yourLuckyNumber + '. Mine is: ' + myLuckyNumber + '. They ' + (yourLuckyNumber == myLuckyNumber ? 'DID ' : 'did NOT ') + 'match!';
    }



    console.log('doing JS in body-section');
    document.writeln('<p class="green">Hello World from JS within a body-section in HTML!</p>');
})();