Reputation: 28116
Often while reading JavaScript source code I see these two lines together on the top.
/* jshint globalstrict: true */
'use strict';
Now, I very well know the purpose of 'use strict';
.
Can someone enlighten me why jshint globalstrict
is included ?
Upvotes: 6
Views: 1169
Reputation: 129839
JSHint (forked from JSLint) is a popular "lint checker" that's run on JavaScript code. It doesn't execute or modify the code, but analyzes it and reports a variety of different potential errors or bad practices that it finds.
If you have 'use strict';
at the top of your JavaScript file, outside of any JavaScript functions, it will enable strict mode for the entire file. By default, JSHint will report a warning if it sees this.
'use strict';
window.permissions = null;
function initialize() {
window.permissions = 0;
}
Warnings
1: Use the function form of "use strict".
This is because many people automatically concatenate their JavaScript files together before sending them to the user, and in those cases the top-level 'use strict;'
can cause bugs. For example, if you have 'use strict';
at the top of main.js
, and it's concatenated with the non-strict-mode controls.js
, strict mode will unintentionally also be applied to the code from controls.js
, potentially changing its behaviour.
// This code is fine on its own, but will break if strict mode is applied.
document.querySelector('.upgade').onclick = function() {
window.permissions = 0777;
}
If this could happen in your case, you should avoid 'use strict';
at the top-level of your file. You could the entire file in a self-executing function to avoid side-effects of concatenation.
(function() {
'use strict';
window.permissions = null;
function initialize() {
window.permissions = 0;
}
}());
However, if you're sure that you don't need to worry about concatenation and don't want to modify your code, the globalstrict
option for JSHint will disable this warning. It's also possible to specify JSHint options using a .jshintrc
file or the --config
command-line flag, but in many cases the this "inline configuration" you saw—using a comment in the file—is easiest.
/* jshint globalstrict: true */
Upvotes: 6