JsLint'超出范围'错误

编程入门 行业动态 更新时间:2024-10-08 04:33:47
本文介绍了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'超出范围'错误

本文发布于:2023-10-23 02:24:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519467.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   JsLint

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!