JsLint'超出范围'错误 [英] JsLint 'out of scope' error

查看:122
本文介绍了JsLint'超出范围'错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

test();

当我使用JsLint检查时,我的JS代码中出现超出范围错误我很有意义。所以我很快就创造了一个例子。这段代码是否存在实际问题,因为变量最终会被提升到函数的顶部。

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.

推荐答案

var 将变量本地化为函数并且需要提升,大多数语言都有块范围而不是函数范围。

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

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

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

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();

您可以使用多个变量:

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

这篇关于JsLint'超出范围'错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆