首页  >  文章  >  web前端  >  关于js的规范

关于js的规范

不言
不言原创
2018-04-10 11:46:191490浏览

本篇文章给大家分享的内容是关于js的规范 问题,具有一定的参考价值有需要的朋友可以参考一下


目录

  • 嵌入规则

  • 对齐缩进与换行

  • 命名

  • 声明

  • 类型

  • 对象

  • 数组

  • 字符串

  • 函数

  • 属性

  • 变量

  • 条件表达式和等号

  • 注释

  • 空白

  • 逗号

  • 分号

  • 类型转换

  • 命名约定

  • 存取器

  • 构造器

  • 事件

  • 模块

  • jQuery

嵌入规则


Javascript程序应该尽量放在.js的文件中,需要调用的时候在页面中以0baaeecebbe44862882dd0f4f2ad526a的形式包含进来。Javascript代码若不是该页面专用的,则应尽量避免在页面中直接编写Javascript代码。

对齐缩进与换行

  • 缩进

    • 在同一系统中应采用同一种缩进标准,本文提倡缩进大小为4个空格。各编译器对Tab键所代替的空白大小定义不同。建议在设置开发环境时,将编辑器里的Tab快捷键重新设置成4个空格。多数编译器提供了此功能。否则建议按4次空格来进行缩进。

  • 换行

    在以下位置必须换行:

    • 每个独立语句结束后;

    • if、else、catch、finally、while等关键字前;

    • 运算符处换行时,运算符必须在新行的行首。

    • 对于因为单行长度超过限制时产生的换行,参考行长度中的策略进行分隔。

  1. 字符串过长截断

每行代码应小于80个字符。若代码较长应尽量换行,换行应选择在操作符和标点符号之后,最好是在分号“;”或逗号“,”之后。下一行代码相对上一行缩进4个空格。这样可以有效防止复制粘贴引起的代码缺失等错误并增强可读性。

  1. 三元运算符过长

三元运算符由3部分组成,因此其换行应当根据每个部分的长度不同,形成3种不同的情况:

<script>    // 无需换行
    var result = condition ? resultA : resultB;    // 条件超长的情况
    var result = thisIsAVeryVeryLongCondition     ? resultA : resultB;    //  结果分支超长的情况
    var result = condition
        ? thisIsAVeryVeryLongCondition
        :resultB;    var result = condition
        ? resultA
        : thisIsAVeryVeryLongCondition;</script>

不得出现以下情况:

<script>    // 最后一个结果很长,但不建议合并条件和第一个分支
    // 不要这么干
    var result = condition ? resultA
        : thisIsAVeryVeryLongCondition;</script>
  1. 过长的逻辑条件组合

当因为较复杂的逻辑条件组合导致80个字符无法满足需求时,应当将每个条件独立一行,逻辑运算符放置在行首进行分隔,或将部分逻辑按逻辑组合进行分隔。最终将右括号)与左大括号{放在独立一行,保证与if内语句块能容易视觉辨识。如:

<script>    // 注意逻辑运算符前的缩进
    if (user.isAuthenticated()
        && user.isInRole(&#39;admin&#39;)
        && user.hasAuthority(&#39;add-admin&#39;)
        || user.hasAuthority(&#39;delete-admin&#39;)
    ) {        // code
    }
</script>
  1. 过长的JSON和数组

如果对象属性较多导致每个属性一行占用空间过大,可以按语义或逻辑进行分组的组织,如:

<script>    // 引文-数字的映射
    var mapping = {
        one: 1, two: 2, three: 3, four: 4, five: 5,
        six: 6, seven: 7, eight:8, nine: 9, ten: 10,
        eleven: 11
    }
</script>

通过5个一组的分组,将每一行控制在合理的范围内,并且按逻辑进行了切分。 对于项目较多的数组,也可以采用相同的方法

  1. eturn语句

return如果用表达式的执行作为返回值,请把表达式和 return 放在同一行中,以免换行符被误解析为语句的结束而引起返回错误。return 关键字后若没有返回表达式,则返回 undefined。构造器的默认返回值为 this。

命名

命名的方法通常有以下几类:
 1. 命名法说明
     - 1).camel命名法,形如thisIsAnApple  
     - 2).pascal命名法,形如ThisIsAnApple
     - 3).下划线命名法,形如this_is_an_apple ·  
     - 4).中划线命名法,形如this-is-an-apple  
 根据不同类型的内容,必须严格采用如下的命名法:

  1. 变量名:必须使用camel命名法

  2. 参数名:必须使用camel命名法

  3. 函数名:必须使用camel命名法

  4. 方法/属性:必须使用camel命名法

  5. 私有(保护)成员:必须以下划线_开头

  6. 常量名:必须使用全部大写的下划线命名法,如IS_DEBUG_ENABLED

  7. 类名:必须使用pascal命名法

  8. 枚举名:必须使用pascal命名法

  9. 枚举的属性:必须使用全部大写的下划线命名法

  10. 命名空间:必须使用camel命名法

  11. 语义:命名同时还需要关注语义,如:  

  • 变量名应当使用名词;

  • boolean类型的应当使用is、has等起头,表示其类型;·

  • 函数名应当用动宾短语;

  • 类名应当用名词。

声明

变量的声明

尽管 JavaScript 语言并不要求在变量使用前先对变量进行声明。但我们还是应该养成这个好习惯。这样可以比较容易的检测出那些未经声明的变量,避免其变为隐藏的全局变量,造成隐患。

在函数的开始应先用 var 关键字声明函数中要使用的局部变量,注释变量的功能及代表的含义,且应以字母顺序排序。每个变量单独占一行,以便添加注释。这是因为 JavaScript 中只有函数的 {} 表明作用域,用 var 关键字声明的局部变量只在函数内有效,而未经 var 声明的变量则被视为全局变量。示例:

<script>    var valueA = "a";    var valueB = "b";    function f1() {
        var valueA = "c";
        alert("valueA=" + valueA); // output: valueA=c
        valueB = "d";
        alert("valueB=" + valueB); // output: valueB=d
    }
    f1();
    alert("valueA=" + valueA); // output: valueA=a
    alert("valueB=" + valueB); // output: valueB=d</script>

用 var 声明过的变量 valueA 和没有声明的变量 valueB 是有区别的。特别需要注意的是,在函数内部用 var 声明的变量为局部变量,这样可以有效地避免因局部变量和全局变量同名而产生的错误。

类型

  • 原始值: 相当于传值

    • string

    • number

    • boolean

    • null

    • undefined

<script>    var foo = 1,
        bar = foo;
    bar = 9;
console.log(foo, bar); // => 1, 9</script>
  • 复杂类型: 相当于传引用

    • object

    • array

    • function

<script>    var foo = [1, 2],
        bar = foo;
    bar[0] = 9;
    console.log(foo[0], bar[0]); // => 9, 9</script>

对象

  • 使用字面值创建对象

<script>// badvar item = new Object();// goodvar item = {};</script>
  • 不要使用保留字 reserved words 作为键

<script>// badvar superman = {  class: &#39;superhero&#39;,  default: { clark: &#39;kent&#39; },
  private: true};// goodvar superman = {
  klass: &#39;superhero&#39;,
  defaults: { clark: &#39;kent&#39; },
  hidden: true};</script>

数组

  • 使用字面值创建数组

<script>// badvar items = new Array();// goodvar items = [];</script>
  • 如果你不知道数组的长度,使用push

<script>var someStack = [];// badsomeStack[someStack.length] = &#39;abracadabra&#39;;// goodsomeStack.push(&#39;abracadabra&#39;);</script>
  • 当你需要拷贝数组时使用slice. jsPerf

<script>var len = items.length,
    itemsCopy = [],
    i;// badfor (i = 0; i < len; i++) {
  itemsCopy[i] = items[i];
}// gooditemsCopy = items.slice();</script>
  • 使用slice将类数组的对象转成数组

<script>function trigger() {
  var args = Array.prototype.slice.call(arguments);
  ...
}
</script>

字符串

  • 对字符串使用单引号 ”

<script>// badvar name = "Bob Parr";// goodvar name = &#39;Bob Parr&#39;;// badvar fullName = "Bob " + this.lastName;// goodvar fullName = &#39;Bob &#39; + this.lastName;</script>
  • 超过80个字符的字符串应该使用字符串连接换行

  • 注: 如果过度使用,长字符串连接可能会对性能有影响

<script>// badvar errorMessage = &#39;This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.&#39;;// badvar errorMessage = &#39;This is a super long error that \
was thrown because of Batman. \
When you stop to think about \
how Batman had anything to do \
with this, you would get nowhere \
fast.&#39;;// goodvar errorMessage = &#39;This is a super long error that &#39; +  &#39;was thrown because of Batman.&#39; +  &#39;When you stop to think about &#39; +  &#39;how Batman had anything to do &#39; +  &#39;with this, you would get nowhere &#39; +  &#39;fast.&#39;;</script>
  • 编程时使用join而不是字符串连接来构建字符串,特别是IE

<script>var items,
    messages,
    length, i;

messages = [{
    state: &#39;success&#39;,
    message: &#39;This one worked.&#39;},{
    state: &#39;success&#39;,
    message: &#39;This one worked as well.&#39;},{
    state: &#39;error&#39;,
    message: &#39;This one did not work.&#39;}];

length = messages.length;// badfunction inbox(messages) {
  items = &#39;<ul>&#39;;  for (i = 0; i < length; i++) {
    items += &#39;<li>&#39; + messages[i].message + &#39;</li>&#39;;
  }  return items + &#39;</ul>&#39;;
}// goodfunction inbox(messages) {
  items = [];  for (i = 0; i < length; i++) {
    items[i] = messages[i].message;
  }  return &#39;<ul><li>&#39; + items.join(&#39;</li><li>&#39;) + &#39;</li></ul>&#39;;
}
</script>

函数

  • 函数表达式:

<script>// 匿名函数表达式var anonymous = function() {
  return true;
};// 有名函数表达式var named = function named() {
  return true;
};// 立即调用函数表达式(function() {
  console.log(&#39;Welcome to the Internet. Please follow me.&#39;);
})();</script>
  • 绝对不要在一个非函数块里声明一个函数,把那个函数赋给一个变量。浏览器允许你这么做,但是它们解析不同。

  • 注: ECMA-262定义把块定义为一组语句,函数声明不是一个语句.

<script>// badif (currentUser) {  function test() {
    console.log(&#39;Nope.&#39;);
  }
}// goodif (currentUser) {  var test = function test() {
    console.log(&#39;Yup.&#39;);
  };
}

</script>
  • 绝对不要把参数命名为 arguments, 这将会逾越函数作用域内传过来的 arguments 对象.

<script>// badfunction nope(name, options, arguments) {
  // ...stuff...}// goodfunction yup(name, options, args) {
  // ...stuff...}
</script>

属性

  • 当使用变量访问属性时使用中括号.

<script>var luke = {
  jedi: true,
  age: 28};function getProp(prop) {
  return luke[prop];
}var isJedi = getProp(&#39;jedi&#39;);</script>

变量

  • 总是使用 var 来声明变量,如果不这么做将导致产生全局变量,我们要避免污染全局命名空间。

<script>// badsuperPower = new SuperPower();// goodvar superPower = new SuperPower();</script>
  • 使用一个 var 以及新行声明多个变量,缩进4个空格。

<script>// badvar items = getItems();var goSportsTeam = true;var dragonball = &#39;z&#39;;// goodvar items = getItems(),
    goSportsTeam = true,
    dragonball = &#39;z&#39;;</script>
  • 最后再声明未赋值的变量,当你想引用之前已赋值变量的时候很有用。

<script>// badvar i, len, dragonball,
    items = getItems(),
    goSportsTeam = true;// badvar i, items = getItems(),
    dragonball,
    goSportsTeam = true,
    len;// goodvar items = getItems(),
    goSportsTeam = true,
    dragonball,
    length,
    i;</script>
  • 在作用域顶部声明变量,避免变量声明和赋值引起的相关问题。

<script>// badfunction() {
  test();
  console.log(&#39;doing stuff..&#39;);  //..other stuff..

  var name = getName();  if (name === &#39;test&#39;) {    return false;
  }  return name;
}// goodfunction() {
  var name = getName();

  test();
  console.log(&#39;doing stuff..&#39;);  //..other stuff..

  if (name === &#39;test&#39;) {    return false;
  }  return name;
}// badfunction() {
  var name = getName();  if (!arguments.length) {    return false;
  }  return true;
}// goodfunction() {
  if (!arguments.length) {    return false;
  }  var name = getName();  return true;
}
</script>

条件表达式和等号

  • 适当使用 === 和 !== 以及 == 和 !=

  • 条件表达式的强制类型转换遵循以下规则:

    • 对象 被计算为 true

    • Undefined 被计算为 false

    • Null 被计算为 false

    • 布尔值 被计算为 布尔的值

    • 数字 如果是 +0, -0, or NaN 被计算为 false , 否则为 true

    • 字符串 如果是空字符串 ” 则被计算为 false, 否则为 true


    • javascript 
      <script> 
      if ([0]) { 
      // true 
      // An array is an object, objects evaluate to true 
      } 
      </script>
  • 使用快捷方式

<script>// badif (name !== &#39;&#39;) {  // ...stuff...}// goodif (name) {  // ...stuff...}// badif (collection.length > 0) {  // ...stuff...}// goodif (collection.length) {  // ...stuff...}
</script>

  • 给所有多行的块使用大括号

<script>// badif (test)  return false;// goodif (test) return false;// goodif (test) {  return false;
}// badfunction() { return false; }// goodfunction() {
  return false;
}
</script>

注释

注释要尽量简单,清晰明了。着重注释的意思,对不太直观的部分进行注解

JavaScript 的注释有两种”//” 和”/* …. */”
 - 建议”//”用作代码行注释
 - “/* …. */”形式用作对整个代码段的注销,或较正式的声明中,如函数参数、功能、文件功能等的描述中
 - >另:复制粘贴应注意注释是否与代码对应。

  • 使用 /* … / 进行多行注释,包括描述,指定类型以及参数值和返回值

<script>// bad// make() returns a new element// based on the passed in tag name//// @param <String> tag// @return <Element> elementfunction make(tag) {

  // ...stuff...

  return element;
}// good/**
 * make() returns a new element
 * based on the passed in tag name
 *
 * @param <String> tag
 * @return <Element> element
 */function make(tag) {

  // ...stuff...

  return element;
}
</script>
  • 使用 // 进行单行注释,在评论对象的上面进行单行注释,注释前放一个空行.

<script>// badvar active = true;  // is current tab// good// is current tabvar active = true;// badfunction getType() {
  console.log(&#39;fetching type...&#39;);  // set the default type to &#39;no type&#39;
  var type = this._type || &#39;no type&#39;;  return type;
}// goodfunction getType() {
  console.log(&#39;fetching type...&#39;);  // set the default type to &#39;no type&#39;
  var type = this._type || &#39;no type&#39;;  return type;
}
</script>
  • 如果你有一个问题需要重新来看一下或如果你建议一个需要被实现的解决方法的话需要在你的注释前面加上 FIXME 或 TODO 帮助其他人迅速理解

<script>function Calculator() {

  // FIXME: shouldn&#39;t use a global here
  total = 0;  return this;
}function Calculator() {

  // TODO: total should be configurable by an options param
  this.total = 0;  return this;
}
</script>

空白

  • 将tab设为4个空格

    // badfunction() {∙∙var name;
    }// badfunction() {∙var name;
    }// goodfunction() {∙∙∙∙var name;
    }
  • 大括号前放一个空格

    // badfunction test(){console.log(&#39;test&#39;);
    }// goodfunction test() {console.log(&#39;test&#39;);
    }// baddog.set(&#39;attr&#39;,{
    age: &#39;1 year&#39;,
    breed: &#39;Bernese Mountain Dog&#39;});// gooddog.set(&#39;attr&#39;, {
    age: &#39;1 year&#39;,
    breed: &#39;Bernese Mountain Dog&#39;});
  • 在做长方法链时使用缩进.

    // bad$(&#39;#items&#39;).find(&#39;.selected&#39;).highlight().end().find(&#39;.open&#39;).updateCount();// good$(&#39;#items&#39;)
    .find(&#39;.selected&#39;)
      .highlight()
      .end()
    .find(&#39;.open&#39;)
      .updateCount();// badvar leds = stage.selectAll(&#39;.led&#39;).data(data).enter().append(&#39;svg:svg&#39;).class(&#39;led&#39;, true)
      .attr(&#39;width&#39;,  (radius + margin) * 2).append(&#39;svg:g&#39;)
      .attr(&#39;transform&#39;, &#39;translate(&#39; + (radius + margin) + &#39;,&#39; + (radius + margin) + &#39;)&#39;)
      .call(tron.led);// goodvar leds = stage.selectAll(&#39;.led&#39;)
      .data(data)
    .enter().append(&#39;svg:svg&#39;)
      .class(&#39;led&#39;, true)
      .attr(&#39;width&#39;,  (radius + margin) * 2)
    .append(&#39;svg:g&#39;)
      .attr(&#39;transform&#39;, &#39;translate(&#39; + (radius + margin) + &#39;,&#39; + (radius + margin) + &#39;)&#39;)
      .call(tron.led);

逗号

  • 不要将逗号放前面

    // badvar once
    , upon
    , aTime;// goodvar once,
      upon,
      aTime;// badvar hero = {
      firstName: &#39;Bob&#39;, lastName: &#39;Parr&#39;, heroName: &#39;Mr. Incredible&#39;, superPower: &#39;strength&#39;};// goodvar hero = {
    firstName: &#39;Bob&#39;,
    lastName: &#39;Parr&#39;,
    heroName: &#39;Mr. Incredible&#39;,
    superPower: &#39;strength&#39;};
  • 不要加多余的逗号,这可能会在IE下引起错误,同时如果多一个逗号某些ES3的实现会计算多数组的长度。

    // badvar hero = {
    firstName: &#39;Kevin&#39;,
    lastName: &#39;Flynn&#39;,
    };var heroes = [&#39;Batman&#39;,&#39;Superman&#39;,
    ];// goodvar hero = {
    firstName: &#39;Kevin&#39;,
    lastName: &#39;Flynn&#39;};var heroes = [&#39;Batman&#39;,&#39;Superman&#39;];

分号

  • 语句结束一定要加分号

    // bad(function() {var name = &#39;Skywalker&#39;return name
    })()// good(function() {var name = &#39;Skywalker&#39;;return name;
    })();// good;(function() {var name = &#39;Skywalker&#39;;return name;
    })();

类型转换

  • 在语句的开始执行类型转换.

  • 字符串:

    //  => this.reviewScore = 9;// badvar totalScore = this.reviewScore + &#39;&#39;;// goodvar totalScore = &#39;&#39; + this.reviewScore;// badvar totalScore = &#39;&#39; + this.reviewScore + &#39; total score&#39;;// goodvar totalScore = this.reviewScore + &#39; total score&#39;;
  • 对数字使用 parseInt 并且总是带上类型转换的基数.

    var inputValue = &#39;4&#39;;// badvar val = new Number(inputValue);// badvar val = +inputValue;// badvar val = inputValue >> 0;// badvar val = parseInt(inputValue);// goodvar val = Number(inputValue);// goodvar val = parseInt(inputValue, 10);// good/**
    * parseInt was the reason my code was slow.
    * Bitshifting the String to coerce it to a
    * Number made it a lot faster.
    */var val = inputValue >> 0;
  • 布尔值:

    var age = 0;// badvar hasAge = new Boolean(age);// goodvar hasAge = Boolean(age);// goodvar hasAge = !!age;

命名约定

  • 避免单个字符名,让你的变量名有描述意义。

    // badfunction q() {// ...stuff...}// goodfunction query() {// ..stuff..}
  • 当命名对象、函数和实例时使用驼峰命名规则

    // badvar OBJEcttsssss = {};var this_is_my_object = {};var this-is-my-object = {};function c() {};var u = new user({
    name: &#39;Bob Parr&#39;});// goodvar thisIsMyObject = {};function thisIsMyFunction() {};var user = new User({
    name: &#39;Bob Parr&#39;});
  • 当命名构造函数或类时使用驼峰式大写

    // badfunction user(options) {this.name = options.name;
    }var bad = new user({
    name: &#39;nope&#39;});// goodfunction User(options) {this.name = options.name;
    }var good = new User({
    name: &#39;yup&#39;});
  • 命名私有属性时前面加个下划线 _

    // badthis.__firstName__ = &#39;Panda&#39;;this.firstName_ = &#39;Panda&#39;;// goodthis._firstName = &#39;Panda&#39;;
  • 当保存对 this 的引用时使用 _this.

    // badfunction() {var self = this;return function() {
      console.log(self);
    };
    }// badfunction() {var that = this;return function() {
      console.log(that);
    };
    }// goodfunction() {var _this = this;return function() {
      console.log(_this);
    };
    }

存取器

  • 属性的存取器函数不是必需的

  • 如果你确实有存取器函数的话使用getVal() 和 setVal(‘hello’)

    // baddragon.age();// gooddragon.getAge();// baddragon.age(25);// gooddragon.setAge(25);
  • 如果属性是布尔值,使用isVal() 或 hasVal()

    // badif (!dragon.age()) {return false;
    }// goodif (!dragon.hasAge()) {return false;
    }
  • 可以创建get()和set()函数,但是要保持一致

    function Jedi(options) {options || (options = {});var lightsaber = options.lightsaber || &#39;blue&#39;;this.set(&#39;lightsaber&#39;, lightsaber);
    }
    
    Jedi.prototype.set = function(key, val) {this[key] = val;
    };
    
    Jedi.prototype.get = function(key) {return this[key];
    };

构造器

  • 给对象原型分配方法,而不是用一个新的对象覆盖原型,覆盖原型会使继承出现问题。

    function Jedi() {console.log(&#39;new jedi&#39;);
    }// badJedi.prototype = {
    fight: function fight() {
      console.log(&#39;fighting&#39;);
    },
    
    block: function block() {
      console.log(&#39;blocking&#39;);
    }
    };// goodJedi.prototype.fight = function fight() {console.log(&#39;fighting&#39;);
    };
    
    Jedi.prototype.block = function block() {console.log(&#39;blocking&#39;);
    };
  • 方法可以返回 this 帮助方法可链。

    // badJedi.prototype.jump = function() {this.jumping = true;return true;
    };
    
    Jedi.prototype.setHeight = function(height) {this.height = height;
    };var luke = new Jedi();
    luke.jump(); // => trueluke.setHeight(20) // => undefined// goodJedi.prototype.jump = function() {this.jumping = true;return this;
    };
    
    Jedi.prototype.setHeight = function(height) {this.height = height;return this;
    };var luke = new Jedi();
    
    luke.jump()
    .setHeight(20);
  • 可以写一个自定义的toString()方法,但是确保它工作正常并且不会有副作用。

    function Jedi(options) {options || (options = {});this.name = options.name || &#39;no name&#39;;
    }
    
    Jedi.prototype.getName = function getName() {return this.name;
    };
    
    Jedi.prototype.toString = function toString() {return &#39;Jedi - &#39; + this.getName();
    };

事件

  • 当给事件附加数据时,传入一个哈希而不是原始值,这可以让后面的贡献者加入更多数据到事件数据里而不用找出并更新那个事件的事件处理器

    // bad$(this).trigger(&#39;listingUpdated&#39;, listing.id);
    
    ...
    
    $(this).on(&#39;listingUpdated&#39;, function(e, listingId) {// do something with listingId});

    更好:

    // good$(this).trigger(&#39;listingUpdated&#39;, { listingId : listing.id });
    
    ...
    
    $(this).on(&#39;listingUpdated&#39;, function(e, data) {// do something with data.listingId});

模块

  • 模块应该以 ! 开始,这保证了如果一个有问题的模块忘记包含最后的分号在合并后不会出现错误

  • 这个文件应该以驼峰命名,并在同名文件夹下,同时导出的时候名字一致

  • 加入一个名为noConflict()的方法来设置导出的模块为之前的版本并返回它

  • 总是在模块顶部声明 'use strict';

    // fancyInput/fancyInput.js!function(global) {&#39;use strict&#39;;var previousFancyInput = global.FancyInput;function FancyInput(options) {
      this.options = options || {};
    }
    
    FancyInput.noConflict = function noConflict() {
      global.FancyInput = previousFancyInput;  return FancyInput;
    };
    
    global.FancyInput = FancyInput;
    }(this);

jQuery

  • 缓存jQuery查询

    // badfunction setSidebar() {$(&#39;.sidebar&#39;).hide();// ...stuff...$(&#39;.sidebar&#39;).css({  &#39;background-color&#39;: &#39;pink&#39;});
    }// goodfunction setSidebar() {var $sidebar = $(&#39;.sidebar&#39;);
    $sidebar.hide();// ...stuff...$sidebar.css({  &#39;background-color&#39;: &#39;pink&#39;});
    }
  • 对DOM查询使用级联的 $('.sidebar ul')$('.sidebar ul'),jsPerf

  • 对有作用域的jQuery对象查询使用 find

    // bad$(&#39;.sidebar&#39;, &#39;ul&#39;).hide();// bad$(&#39;.sidebar&#39;).find(&#39;ul&#39;).hide();
  • // good$(&#39;.sidebar ul&#39;).hide();// good$(&#39;.sidebar > ul&#39;).hide();// good (slower)$sidebar.find(&#39;ul&#39;);// good (faster)$($sidebar[0]).find(&#39;ul&#39;);

以上是关于js的规范 的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
上一篇:JS中的判断类型下一篇:JS的延时器