如何在JSLint中全局设置'use strict'

9
我刚开始学习 JavaScript,正在尝试通过 JSLint 进行验证。 我应该把"use strict"放在哪里以便全局使用并进行验证?
这会给我一个错误提示:"Unexpected expression 'use strict' in statement position.":
    "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个回答

6
根据文档,JSLint的browser选项会自动禁用全局级别的"use strict";。据我所知,没有办法重新启用它。
您可以关闭browser选项,并使用以下内容获得与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

'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>');
})();

4
"use strict"; 可以完全放置于文件开头,这是合法的。 - T.J. Crowder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接