当我使用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'超出范围'错误
发布评论