What is the reason behind JSLint saying there are “too many var statements”

后端 未结 7 1107
时光说笑
时光说笑 2020-12-13 12:06

JSLint (with the onevar flag turned on) is flagging some javascript code that I have with the following:

Problem at line 5 character 15: Too many var statements.

        
相关标签:
7条回答
  • 2020-12-13 12:38

    The official reason is here, by Douglas Crockford.

    To quote:

    In many languages, a block introduces a scope. Variables introduced in a block are not visible outside of the block.

    In JavaScript, blocks do not introduce a scope. There is only function-scope. A variable introduced anywhere in a function is visible everywhere in the function. JavaScript's blocks confuse experienced programmers and lead to errors because the familiar syntax makes a false promise.

    JSLint expects blocks with function, if, switch, while, for, do, and try statements and nowhere else.

    In languages with block scope, it is usually recommended that variables be declared at the site of first use. But because JavaScript does not have block scope, it is wiser to declare all of a function's variables at the top of the function. It is recommended that a single var statement be used per function. This can be declined with the vars option.

    0 讨论(0)
  • 2020-12-13 12:38

    Just a guess here, but it may be time for functional decomposition. Functions should do one thing and do it well.

    Too many vars is suggestive of a function that's trying to do too much. Or a case where you should be using an array.

    0 讨论(0)
  • 2020-12-13 12:41

    Javascript does not have block scope. In other languages with it (like c), if you declare a variable in the if statement, you can not access it outside of it, but in javascript you can. The author of JSLint believes it is a bad practice, since you (or other readers) might get confused and think that you can no longer access the variable, but you actually can. Therefore, you should declare all your variables at the top of the function.

    0 讨论(0)
  • 2020-12-13 12:51

    Just declare your vars in one place like this:

    var request,x,y;
    
    0 讨论(0)
  • 2020-12-13 12:52

    The idea is that you should use an object instead of individual vars. So where you have got:

    var x = arg + 1,
        y = cache.GetItem('xyz');
    

    Change it to:

    var dimensions = {};
    dimensions.x = arg + 1;
    dimensons.y = cache.GetItem('xyz');
    dimensions.request = ...
    

    You can then access these variables through the object, its neater to have one object per function to contain that functions variables. Then you won't get the warning.

    0 讨论(0)
  • 2020-12-13 12:54

    If the "onevar" option is set to true if only one var statement per function is allowed.

    if (funct['(onevar)'] && option.onevar) {
        warning("Too many var statements.");
    }
    
    0 讨论(0)
提交回复
热议问题