Try to use one var statement per scope in JavaScript[转]

[原文地址:http://www.cnblogs.com/JulyZhang/archive/2011/03/10/1979619.html]

 

今天在使用 YUI Compressor 压缩 javascript 时,遇到 "Try to use one var statement per scope in JavaScript" 的warning提示,问题出在 var 声明问题上,下文解释了原因。

 

 

JavaScript’s var statement declares and optionally initializes one or more variables in the scope of the current function (or as global variables when used outside a function). Since var accepts multiple declarations, separated by commas, there’s usually no reason to use it more than once per function; it’s just a waste of bytes and—especially if you redeclare variables inside a loop—CPU cycles.

Overuse of var statements is one of the most common problems I see in JavaScript code. I was guilty of it myself for quite a while and it took me a long time to break the habit.

 

Bad:
function getElementsByClassName(className, tagName, root) {
  var elements = [];
  var root     = root || document;
  var tagName  = tagName || '*';
  var haystack = root.getElementsByTagName(tagName);
  var regex    = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');
 
  for (var i = 0, length = haystack.length; i < length; ++i) {
    var el = haystack[i];
 
    if (el.className && regex.test(el.className)) {
      elements.push(el);
    }
  }
 
  return elements;
}

 

There are several things wrong with the example above.

The most obvious problem is that I’ve used the var statement no less than seven times. Somewhat less obvious, but far worse: I’ve used it inside a loop, which means that I’m unnecessarily redeclaring a variable on each iteration. I’ve also unnecessarily redeclared two variables that were passed in as function arguments.

Naturally, there’s a much better way to do this.

 

Good:
function getElementsByClassName(className, tagName, root) {
  root    = root || document;
  tagName = tagName || '*';

  var elements = [],
      haystack = root.getElementsByTagName(tagName),
      length   = haystack.length,
      regex    = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'),
      el, i;

  for (i = 0; i < length; ++i) {
    el = haystack[i];

    if (el.className && regex.test(el.className)) {
      elements.push(el);
    }
  }

  return elements;
}

 

There are circumstances in which it is actually necessary to redeclare a variable within a single scope, but they’re very rare, and are more often than not a warning sign that you need to rethink the code you’re writing.

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值