Avoiding implied global variables in javascript (JSlint)

When writing code like this, jsLint complains about implied global variables:

var Test = (function(){
    var fnc = function(x){
        alert("pew: "+x);
    };

    return {
        fnc: fnc
    };
}());

Test.fnc("hat");

(in particular, “Implied Global: Warning 4”)

What is considered the right way to avoid this? My instinctive answer is this, but I'm not sure if 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 is not that I am addressing the global, the more I am not telling jslint what global is. I will leave it open a little longer to find out if there is anyone else, and I will answer.

+5
source share
4 answers

You can add a comment file.

/*global alert $ document window*/

, JSLint, , .

, -, , .

+8

jsLint " " ", , ,...", jsLint. . http://www.jslint.com/lint.html#options .

+4

, JSHint, "", ​​ "true" . "jquery". gradle -js-plugin .

+1

I think your path is correct (and good too), but there is no need to declare global.alert, just useglobal.alert("pew: "+x);

0
source

All Articles