Javascript JsLint“超出范围”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2485171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:34:33  来源:igfitidea点击:

JsLint 'out of scope' error

javascriptjslint

提问by Rajat

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. Is there something actually wrong with this code piece, as the variable is eventually hoisted to the top of the function anyways.

当我使用 JsLint 检查时,我的 JS 代码中不断出现“超出范围”错误,这对我来说毫无意义。所以我很快创建了一个示例。这段代码是否真的有问题,因为无论如何变量最终都会被提升到函数的顶部。

回答by Quentin

While varlocalizes 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 recommendsusing a single varstatement 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;
    // …
}

回答by Itay Maman

The code that you wrote is working. It is just not very readable/maintainable. Declaring the variable ainside the scope of the ifmay give the false impression that ais only visible inside this scope (which, as this program shows, is not true - awill 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);
}

回答by kumarras

Javascript have function scope and not block scope. So, variables declared inside if function is visible and accessible outside the if block and within the function in which if statement is declared.

Javascript 有函数作用域而不是块作用域。因此,在 if 函数内声明的变量在 if 块外和声明 if 语句的函数内是可见和可访问的。

Online compilers like JSLint and jsbin give warnings but they are not errors.

像 JSLint 和 jsbin 这样的在线编译器会给出警告,但它们不是错误。