`
edison87915
  • 浏览: 199414 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

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.

 

 

分享到:
评论

相关推荐

    探索深度学习在RollerCoin挖矿的效率 Try to use deep learning techniques.zip

    探索深度学习在RollerCoin挖矿的效率 Try to use deep learning techniques

    javascript-in-one-pic

    "javascript-in-one-pic"这个主题以一张图的形式概述了JavaScript的所有关键知识点,旨在帮助初学者快速理解并记忆JavaScript的核心概念。 首先,这张图可能包含JavaScript的基础语法部分,如变量声明(var、let、...

    JavaScript in 10 Minutes

    "JavaScript in 10 Minutes" is a concise guide that aims to provide intermediate to advanced JavaScript developers with an overview of the language's unique features and nuances. This document is not ...

    Word Per Minute Typing Test in JavaScript Free Source Code.zip

    这个压缩包"Word Per Minute Typing Test in JavaScript Free Source Code.zip"提供了一个用JavaScript实现的打字速度测试游戏的源代码。在这个项目中,我们可以学习到如何利用JavaScript来创建交互式的网页应用。 ...

    javascript in action:javascript 实战源码

    "JavaScript in Action: JavaScript 实战源码"很可能是针对JavaScript编程的一个实践项目或教程,旨在帮助开发者通过实际代码理解JavaScript的工作原理和应用技巧。在这个实战源码中,我们可能涵盖以下JavaScript的...

    基于深度学习的股票预测-Use Deep Learning try to predict stock price.

    【作品名称】:基于深度学习的股票预测-Use Deep Learning try to predict stock price. 【适用人群】:适用于希望学习不同技术领域的小白或进阶学习者。可作为毕设项目、课程设计、大作业、工程实训或初期项目...

    Rediscovering JavaScript

    JavaScript is no longer to be feared or loathed – the world’s most...To try out the examples in the book you will need a computer with Node.js, a text editor, and a browser like Chrome installed in it.

    JSP Simple Examples

    When we have a closely related data of the same type and scope, it is better to declare it in an array. Multidimensional array java A two dimensional array can be thought as a grid of rows and ...

    Mastering+JavaScript+Functional+Programming-Packt+Publishing(2017).pdf

    from the start, and you need not try to abandon every non-functional feature in the language either. JavaScript assuredly has some bad features, but it also has several very good and powerful ones. ...

    JavaScript将当前时间转换成UTC标准时间的方法

    本文实例讲述了JavaScript将当前时间转换成UTC标准时间的方法。分享给大家供大家参考。具体如下: 这里使用JavaScript将当前时间转换成UTC标准时间,北京在东八区,在北京时间基础上减掉8小时 &lt;!DOCTYPE html&gt; &...

    prepareStatement和Statement的区别

    prepareStatement和Statement的区别 prepareStatement和Statement是 Java 中两个常用的数据库操作接口,它们都可以用来执行 SQL 语句,但是它们之间有着明显的区别。 首先,从创建时的区别开始,Statement 需要...

    Number to Bin Converter Using Javascript.zip

    这个"Number to Bin Converter Using Javascript.zip"压缩包可能包含一个实现这一功能的代码示例。下面我们将深入探讨如何使用JavaScript将数字转换为二进制字符串。 在JavaScript中,有内置的方法可以实现这个转换...

    Machine Learning in Python 原版PDF by Bowles

    for themselves each time they want to try a new one. Among general-purpose programming languages, Python developers have been in the forefront, building state-of-the-art machine learning tools, but ...

    Javascript流程控制语句

    ### JavaScript流程控制语句详解 #### 一、语句的定义 在JavaScript中,语句是构成程序逻辑的基本单元,它决定了程序的执行路径。语句可以是单一的命令,也可以是一系列命令组成的复合语句(由一对大括号 `{}` 包围...

    JavaScript学习帮助文档_JavaScript学习帮助文档_javascript_

    JavaScript是一种广泛应用于网页和网络应用的编程语言,尤其在客户端脚本方面占据着核心地位。这份"JavaScript学习帮助文档"是专为初学者设计的,旨在帮助他们掌握JavaScript的基础知识和实际应用技巧。 首先,...

    Javascript.info Ebook Part 1 The JavaScript language (2019).pdf

    文档首先介绍了JavaScript的基础知识,如现代模式的使用,以及`use strict`指令,这个指令用于启用严格模式,帮助开发者写出更好的JavaScript代码。 紧接着介绍了基本的编程元素,包括: - 代码结构,如变量声明和...

    Simple Checker Game in JavaScript Free Source Code.zip

    在本项目中,"Simple Checker Game in JavaScript Free Source Code.zip" 提供了一个使用纯JavaScript编写的简单跳棋游戏的源代码。JavaScript是一种广泛应用于网页和网络应用开发的编程语言,尤其在实现动态交互...

    jboss in action

    One of the things you quickly realize when you work with any of the technologies covered by the Java EE umbrella is that many things are part of the specification, and some things are left as ...

    Mastering+JavaScript+Functional+Programming-Packt+Publishing(2017).epub

    You need not try to apply all of FP from the start, and you need not try to abandon every non-functional feature in the language either. JavaScript assuredly has some bad features, but it also has ...

Global site tag (gtag.js) - Google Analytics