如何在全局范围内使用JSLint设置'use strict'
我是新来的JavaScript,并试图通过JSLint验证。 我应该在哪里放置“严格使用”以在全球范围内使用并验证?
这给了我错误“意外表达'使用严格'在声明的位置。”:
"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>');
根据文档,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";
在全球范围内。
“使用严格”通常用于函数的开始。 对于你的代码,我会把它全部包装在一个IIFE中,这会使'严格'有效
(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>');
})();
链接地址: http://www.djcxy.com/p/90271.html