Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding Implied globals in javascript (JSlint)

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.

like image 595
david Avatar asked Jan 31 '11 23:01

david


1 Answers

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.

like image 157
Raynos Avatar answered Sep 28 '22 11:09

Raynos