最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Avoiding Implied globals in javascript (JSlint) - Stack Overflow

programmeradmin3浏览0评论

When writing code like this jsLint plains 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.

When writing code like this jsLint plains 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.

Share Improve this question edited Jan 31, 2011 at 23:54 david asked Jan 31, 2011 at 23:07 daviddavid 18.3k4 gold badges44 silver badges59 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 8

You can prepend your file with a ment

/*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./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 mon 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);

发布评论

评论列表(0)

  1. 暂无评论