JsLint 'out of scope' error

前端 未结 3 1353
暖寄归人
暖寄归人 2020-12-30 21:31
function test(){
    if(true){
        var a = 5;
    }
    alert(a);
}

test();

I keep getting \'out of scope\' errors in my JS code when I check

3条回答
  •  天命终不由人
    2020-12-30 22:05

    While var localizes a variable to the function and is subject to hoisting, most languages have block scope and not function scope.

    By using the var keyword inside an if block, but accessing the variable outside that block, you've created a construct that can be confusing to people not familiar with that JS idiosyncrasy.

    Douglas Crockford recommends using a single var statement at the top of a function that specifies all the variables that should be scoped to that function.

    function test(){
        var a;
        if(true){
            a = 5;
        }
        alert(a);
    }
    
    test();
    

    With multiple variables you would have:

    function foo () {
        var a, b, c, d = "only d has an initial value", e;
        // …
    }
    

提交回复
热议问题