zoukankan      html  css  js  c++  java
  • [转] Try to use one var statement per scope in JavaScript

    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.

  • 相关阅读:
    前端笔记之移动端&响应式(上)媒体查询&Bootstrap&动画库&zepto&velocity
    SVN的使用
    Git的使用
    前端笔记之HTML5&CSS3(下)2D/3D转换&animate动画
    前端笔记之HTML5&CSS3(中)选择器&伪类伪元素&CSS3效果&渐变背景&过渡
    idea|properties文件乱码
    Web 开发工具类(5) | DateUtils
    Idea | Load error: undefined path variables
    聊聊SpringBoot | 第一章:快速搭建SpringBoot第一个应用
    Springboot | Failed to execute goal org.springframework.boot:spring-boot-maven-plugin
  • 原文地址:https://www.cnblogs.com/JulyZhang/p/1979619.html
Copyright © 2011-2022 走看看