简体   繁体   English

JsLint'超出范围'错误

[英]JsLint 'out of scope' error

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

test();

I keep getting 'out of scope' errors in my JS code when I check with JsLint which make no sense to me.So I quickly created an example. 当我用JsLint检查时,我在JS代码中不断出现“超出范围”的错误,这对我来说毫无意义。所以我很快就创建了一个例子。 Is there something actually wrong with this code piece, as the variable is eventually hoisted to the top of the function anyways. 这段代码是否存在实际问题,因为变量最终会被提升到函数的顶部。

While var localizes a variable to the function and is subject to hoisting, most languages have block scope and not function scope. 虽然var将变量本地化为函数并且需要提升,但大多数语言都有块范围而不是函数范围。

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. 通过在if块中使用var关键字,但访问该块之外的变量,您已经创建了一个可能让那些不熟悉JS特性的人感到困惑的构造。

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. Douglas Crockford建议在函数顶部使用单个var语句,该函数指定应该作用于该函数的所有变量。

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;
    // …
}

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). 声明变量a的范围内if可以给假象, a是仅此范围内可见(其中,作为该计划显示,事实并非如此- a将在整个函数可见)。

This JsLint warning encourages you to place the declaration at the exact scope where the variable is actually used, as follows: 此JsLint警告鼓励您将声明放在实际使用变量的确切范围内,如下所示:

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

Javascript have function scope and not block scope. Javascript具有函数范围而不是块范围。 So, variables declared inside if function is visible and accessible outside the if block and within the function in which if statement is declared. 因此,如果函数是可见的并且在if块之外以及在声明if语句的函数内可访问,则在内部声明的变量。

Online compilers like JSLint and jsbin give warnings but they are not errors. 像JSLint和jsbin这样的在线编译器会发出警告,但它们不是错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM