JsLint 'out of scope' error

前端 未结 3 1330
暖寄归人
暖寄归人 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 21:59

    The code that you wrote is working. It is just not very readable/maintainable. Declaring the variable a inside the scope of the if may give the false impression that a is only visible inside this scope (which, as this program shows, is not true - a will be visible throughout the whole function).

    This JsLint warning encourages you to place the declaration at the exact scope where the variable is actually used, as follows:

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

提交回复
热议问题