JSLint背后有什么原因说“var语句太多”了 [英] What is the reason behind JSLint saying there are "too many var statements"

查看:134
本文介绍了JSLint背后有什么原因说“var语句太多”了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JSLint(打开onevar标志)正在使用以下内容标记我的一些javascript代码:

JSLint (with the onevar flag turned on) is flagging some javascript code that I have with the following:

Problem at line 5 character 15: Too many var statements.

我很乐意解决这些错误,但我想知道,我是为了表现还是因为它只是一个糟糕的做法,并有更大的潜力在我的JavaScript代码中引入错误。 onevar标志背后的原因是什么?

I am happy to fix these errors, but I'd like to know, am I doing it for performance or because it is just a bad practice and has a greater potential to introduce bugs in my javascript code. What is the reason behind the onevar flag?

我确实查看了 var关键字但它没有具体说明为什么同一函数中的多个var语句都不好。

I did look at the JSLint docs for the var keyword but it doesn't specifically talk about why multiple var statements in the same function are bad.

这是一个例子的尝试。解释代码如何只从1个var语句中受益:

Here is an attempt at an example. Explain how the code will benefit from only having 1 var statement:

function Test(arg) {
   var x = arg + 1,
       y = cache.GetItem('xyz');
   if (y !== null) {
      // This is what would cause the warning in JSLint
      var request = ajaxPost(/* Parameters here */);

   }
}


推荐答案

Javascript没有块范围。在其他语言中(如c),如果在if语句中声明一个变量,则不能在它之外访问它,但在javascript中你可以。 JSLint的作者认为这是一种不好的做法,因为你(或其他读者)可能会感到困惑并认为你不能再访问变量,但实际上你可以。因此,您应该在函数顶部声明所有变量。

Javascript does not have block scope. In other languages with it (like c), if you declare a variable in the if statement, you can not access it outside of it, but in javascript you can. The author of JSLint believes it is a bad practice, since you (or other readers) might get confused and think that you can no longer access the variable, but you actually can. Therefore, you should declare all your variables at the top of the function.

这篇关于JSLint背后有什么原因说“var语句太多”了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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