JavaScript代码约定 - 变量声明 [英] JavaScript code conventions - variable declaration

查看:71
本文介绍了JavaScript代码约定 - 变量声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中声明变量的错误较少的方法是什么?

What's the less error prone approach to declare variables in JavaScript?

var a;
var b;
var c;

var a,
    b,
    c;

jQuery和Dojo使用第二种方法,就代码易读性而言,这是我最喜欢的,问题是我觉得调试起来比较困难。

jQuery and Dojo use the second approach and personally that's my favorite in terms of code legibility, the problem is that I find it harder to debug.

示例1:

var a,
    b,
    c; // oops.. semicolon instead of comma
    d,
    e;

示例2:

搜索时项目中的某个变量, var 更好地表明变量已被声明。

When searching for a certain variable in the project, var stands out better that the variable is being declared.

编辑:最初的例子是错误的,我在复制和粘贴时犯了一个错误。代码已经更新,抱歉不方便。

EDIT: The original examples were wrong, i've made a mistake when copying and pasting. The code is already updated, sorry for the incovenient.

推荐答案

多个变量声明(而不是组合)不易出错,因为你提到的原因。但是,组合声明还有其他一些优点:

Multiple variable declarations (rather than combined) are less error prone, for the reasons you mentioned. However, combined declarations have some other advantages:


  • JSLint和其他可能的连接器会抱怨多个 var 每个范围的关键字。

  • 单个 var 关键字比许多更好,原因显而易见。

  • 组合声明会强制您在一个地方声明变量,可能接近它们所在函数的开头,这被认为是一种很好的做法。

  • JSLint and possibly other linters will complain about multiple var keywords per scope.
  • A single var keyword minifies better than many, for obvious reasons.
  • Combining declarations forces you to declare the variables in one place, probably close to the beginning of the function they reside in, which is considered good practice.

另一方面,正如您所提到的,可以使用组合变量声明进行错误,并且它们可能在diff中表现得很笨拙。

On the flipside, as you mentioned mistakes can be made with combined variable declarations, and they can be awkwardly represented in a diff.

只要你在整个项目中保持一致的变量声明风格,你选择的风格就不重要了。

As long as you keep a consistent style of variable declaration throughout the project, the style you choose should not really matter.

这篇关于JavaScript代码约定 - 变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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