When writing code like this jsLint complains about implied globals:
var Test = (function(){
var fnc = function(x){
alert("pew: "+x);
};
return {
fnc: fnc
};
}());
Test.fnc("hat");
(specifically, 'Implied global: alert 4')
What is considered the correct way to avoid this? My instinctive response is this, but I'm not convinced it is 'correct':
var Test2 = (function(global){
var alert = global.alert;
var fnc = function(x){
alert("pew: "+x);
};
return {
开发者_高级运维 fnc: fnc
};
}(this));
Test2.fnc("hat");
Edit: The consensus seems to be that the problem isn't the fact that I'm accessing a global, it's more that I'm not telling jslint what the globals are. I'll leave this open a little longer to see if anyone else has input, then I'll pick an answer.
You can prepend your file with a comment
/*global alert $ document window*/
This is generally how I tell JSLint that it's not implied but external.
This is both unobtrusive as well as telling your fellow programmers that your declaring these variables as external which is useful for larger multi-file programs.
Use jsLint's "assume a browser" and "Assume console, alert, ..." options to make those functions known to jsLint. See http://www.jslint.com/lint.html#options for a list of all available options.
For those searching for JSHint instead, there is an option "browser" which can be set to "true" and handles all the common globals. Same for "jquery". I learned this from the gradle-js-plugin source code.
I think your way is correct(and good too), but there is no need to declare global.alert
, just use global.alert("pew: "+x);
精彩评论