Properties
 
 • 当访问属性的时候,我们使用点(.)操作符。
  1. var luke = {
  2. jedi: true,
  3. age: 28
  4. };
  5.  
  6. // bad
  7. var isJedi = luke['jedi'];
  8.  
  9. // good
  10. var isJedi = luke.jedi;

• 当以变量的方式访问属性的时候,用下标符号([])。——除非特殊需求,否则尽量避免使用obj[variable]的方式进行属性访问。

  1. var luke = {
  2. jedi: true,
  3. age: 28
  4. };
  5.  
  6. function getProp(prop) {
  7. return luke[prop];
  8. }
  9.  
  10. var isJedi = getProp('jedi');
Variables
 
 • 总是使用var定义变量,否则会导致产生隐含全局变量。我们要尽量避免污染全局变量命名空间。
  1. // bad
  2. superPower = new SuperPower();
  3.  
  4. // good
  5. var superPower = new SuperPower();

汤姆大叔—javascript系列文章中提到“JavaScript有隐含的全局概念,意味着你不声明的任何变量都会成为一个全局对象属性。在技术上,隐式全局变量并不是真正的全局变量,但它们是全局对象的属性。属性是可以通过delete操作符删除的,而变量是不能的。"

 • 使用一个var定义多个变量,每个变量在一个新行上。
  1. // bad
  2. var items = getItems();
  3. var goSportsTeam = true;
  4. var dragonball = 'z';
  5.  
  6. // good
  7. var items = getItems(),
  8. goSportsTeam = true,
  9. dragonball = 'z';

• 用var定义多个变量的时候,把不进行赋值的变量放置到最后——这是相当有益的。尤其是当你的变量需要前面变量值的时候。

  1. // bad
  2. var i, len, dragonball,
  3. items = getItems(),
  4. goSportsTeam = true;
  5.  
  6. // bad
  7. var i, items = getItems(),
  8. dragonball,
  9. goSportsTeam = true,
  10. len;
  11.  
  12. // good
  13. var items = getItems(),
  14. goSportsTeam = true,
  15. dragonball,
  16. length,
  17. i;

• 把你的赋值变量放置在当前作用域的顶端。这将避免变量声明和hoisting(悬置/置顶解析/预解析)的问题。

  1. // bad
  2. function() {
  3. test();
  4. console.log('doing stuff..');
  5.  
  6. //..other stuff..
  7.  
  8. var name = getName();
  9.  
  10. if (name === 'test') {
  11. return false;
  12. }
  13.  
  14. return name;
  15. }
  16.  
  17. // good
  18. function() {
  19. var name = getName();
  20.  
  21. test();
  22. console.log('doing stuff..');
  23.  
  24. //..other stuff..
  25.  
  26. if (name === 'test') {
  27. return false;
  28. }
  29.  
  30. return name;
  31. }
  32.  
  33. // bad
  34. function() {
  35. var name = getName();
  36.  
  37. if (!arguments.length) {
  38. return false;
  39. }
  40.  
  41. return true;
  42. }
  43.  
  44. // good
  45. function() {
  46. if (!arguments.length) {
  47. return false;
  48. }
  49.  
  50. var name = getName();
  51.  
  52. return true;
  53. }
Hoisting
 
汤姆大叔:
  1、JavaScript中,你可以在函数的任何位置声明多个var语句,并且它们就好像是在函数顶部声明一样发挥作用,这种行为称为 hoisting(悬置/置顶解析/预解析)。
  2、对于JavaScript,只 要你的变量是在同一个作用域中(同一函数),它都被当做是声明的,即使是它在var声明前使用的时候。
 •  变量声明提升到当前作用域的顶端,而它们的赋值操作不一定要这么做。
  1. function example() {
  2. console.log(notDefined); // => throws a ReferenceError
  3. }
  4.  
  5. function example() {
  6. console.log(declaredButNotAssigned); // => undefined
  7. var declaredButNotAssigned = true;
  8. }
  9.  
  10. function example() {
  11. var declaredButNotAssigned;
  12. console.log(declaredButNotAssigned); // => undefined
  13. declaredButNotAssigned = true;
  14. }

•  匿名表达式会自动提升它们的变量名称(也就是说在var anonymous上面,example函数就已经知道有这个变量了),但是它们的函数体不会。

  1. function example() {
  2. console.log(anonymous); // => undefined
  3.  
  4. anonymous(); // => TypeError anonymous is not a function
  5.  
  6. var anonymous = function() {
  7. console.log('anonymous function expression');
  8. };
  9. }

•  命名函数表达式也会提升它们的变量名称,而它们的函数名称和函数体不会这样做。

  1. function example() {
  2. console.log(named); // => undefined
  3.  
  4. named(); // => TypeError named is not a function
  5.  
  6. superPower(); // => ReferenceError superPower is not defined
  7.  
  8. var named = function superPower() {
  9. console.log('Flying');
  10. };
  11.  
  12. function example() {
  13. console.log(named); // => undefined
  14.  
  15. named(); // => TypeError named is not a function
  16.  
  17. var named = function named() {
  18. console.log('named');
  19. };
  20. }
  21. }

•  注意:函数声明会提升它们的变量名称还有它们的函数体

  1. function example() {
  2. superPower(); // => Flying
  3.  
  4. function superPower() {
  5. console.log('Flying');
  6. }
  7. }
Conditional Expressions & Equality
 
 •  使用 === 和 !== 代替==和!=。
== 和 != 会进行隐式类型转换,所以建议使用===和!==。
 •  强制使用对象的特性(ToBoolean)得到条件表达式的值,大致遵循以下简单规则。
  ◊ Objects 得到的值是true。
  ◊ Undefined得到的值是false。
  ◊ Null得到的值是false。
  ◊ Booleans得到的值是Boolean值(呵呵,当然)。
  ◊ Numbers 得到的值是:如果是+0,-0,或者NaN就是false,否则就是true。
  ◊ Strings 得到的值是:如果是'',就是false,否则就是true。
  1. if ([0]) {
  2. // true
  3. // An array is an object, objects evaluate to true
  4. }

•  使用快捷方式。

  1. // bad
  2. if (name !== '') {
  3. // ...stuff...
  4. }
  5.  
  6. // good
  7. if (name) {
  8. // ...stuff...
  9. }
  10.  
  11. // bad
  12. if (collection.length > 0) {
  13. // ...stuff...
  14. }
  15.  
  16. // good
  17. if (collection.length) {
  18. // ...stuff...
  19. }
  20.  
Blocks
 
• 有{}的代码,我们换行处理。
  1. // bad
  2. if (test)
  3. return false;
  4.  
  5. // good
  6. if (test) return false;
  7.  
  8. // good
  9. if (test) {
  10. return false;
  11. }
  12.  
  13. // bad
  14. function() { return false; }
  15.  
  16. // good
  17. function() {
  18. return false;
  19. }
Comments
 
• 对于多行注释使用/**  ... */。包含描述信息、参数类型和返回值。
 
  1. // bad
  2. // make() returns a new element
  3. // based on the passed in tag name
  4. //
  5. // @param <String> tag
  6. // @return <Element> element
  7. function make(tag) {
  8.  
  9. // ...stuff...
  10.  
  11. return element;
  12. }
  13.  
  14. // good
  15. /**
  16. * make() returns a new element
  17. * based on the passed in tag name
  18. *
  19. * @param <String> tag
  20. * @return <Element> element
  21. */
  22. function make(tag) {
  23.  
  24. // ...stuff...
  25.  
  26. return element;
  27. }
• 对于单行注释使用//。单行注释单独放置在一个新行上。在注释前面放置一个空行。
  1. // bad
  2. var active = true; // is current tab
  3.  
  4. // good
  5. // is current tab
  6. var active = true;
  7.  
  8. // bad
  9. function getType() {
  10. console.log('fetching type...');
  11. // set the default type to 'no type'
  12. var type = this._type || 'no type';
  13.  
  14. return type;
  15. }
  16.  
  17. // good
  18. function getType() {
  19. console.log('fetching type...');
  20.  
  21. // set the default type to 'no type'
  22. var type = this._type || 'no type';
  23.  
  24. return type;
  25. }

• 对于一些问题,注释前加FIXME或TODO,这样将快速帮助开发者快速明白代码意图。

• 使用 // FIXME: 注释问题

  1. function Calculator() {
  2.  
  3. // FIXME: shouldn't use a global here
  4. total = 0;
  5.  
  6. return this;
  7. }

• 使用 // TODO: 注释问题的解决方案

  1. function Calculator() {
  2.  
  3. // TODO: total should be configurable by an options param
  4. this.total = 0;
  5.  
  6. return this;
  7. }
Type Casting & Coercion
 
• 在声明之前执行强制类型转换。
• 字符串
  1. // => this.reviewScore = 9;
  2.  
  3. // bad
  4. var totalScore = this.reviewScore + '';
  5.  
  6. // good
  7. var totalScore = '' + this.reviewScore;
  8.  
  9. // bad
  10. var totalScore = '' + this.reviewScore + ' total score';
  11.  
  12. // good
  13. var totalScore = this.reviewScore + ' total score';

• 对于数字转换,使用parseInt,而且要带着类型转换的基数。

• 如果parseInt成为你的瓶颈,处于性能原因,需要你使用“位移”操作。那么请写下注释解释你这样做的原因。

  1. var inputValue = '4';
  2.  
  3. // bad
  4. var val = new Number(inputValue);
  5.  
  6. // bad
  7. var val = +inputValue;
  8.  
  9. // bad
  10. var val = inputValue >> 0;
  11.  
  12. // bad
  13. var val = parseInt(inputValue);
  14.  
  15. // good
  16. var val = Number(inputValue);
  17.  
  18. // good
  19. var val = parseInt(inputValue, 10);
  20.  
  21. // good
  22. /**
  23. * parseInt 使我的代码变慢.
  24. * 为了提高速度,使用位移操作让字符串强制转化为数字。
  25. */
  26. var val = inputValue >> 0;

• 布尔

  1. var age = 0;
  2.  
  3. // bad
  4. var hasAge = new Boolean(age);
  5.  
  6. // good
  7. var hasAge = Boolean(age);
  8.  
  9. // good
  10. var hasAge = !!age;
Constructors
 
 • 用方法扩展对象,而不是用一个新对象。
  1. function Jedi() {
  2. console.log('new jedi');
  3. }
  4.  
  5. // bad
  6. Jedi.prototype = {
  7. fight: function fight() {
  8. console.log('fighting');
  9. },
  10.  
  11. block: function block() {
  12. console.log('blocking');
  13. }
  14. };
  15.  
  16. // good
  17. Jedi.prototype.fight = function fight() {
  18. console.log('fighting');
  19. };
  20.  
  21. Jedi.prototype.block = function block() {
  22. console.log('blocking');
  23. };
  • 让对象的方法return this,这样有利于方法的链锁操作。
 
  1. // bad
  2. Jedi.prototype.jump = function() {
  3. this.jumping = true;
  4. return true;
  5. };
  6.  
  7. Jedi.prototype.setHeight = function(height) {
  8. this.height = height;
  9. };
  10.  
  11. var luke = new Jedi();
  12. luke.jump(); // => true
  13. luke.setHeight(20) // => undefined
  14.  
  15. // good
  16. Jedi.prototype.jump = function() {
  17. this.jumping = true;
  18. return this;
  19. };
  20.  
  21. Jedi.prototype.setHeight = function(height) {
  22. this.height = height;
  23. return this;
  24. };
  25.  
  26. var luke = new Jedi();
  27.  
  28. luke.jump()
  29. .setHeight(20);

• 我们可以自定义一个toString()方法。——要确保它能正常运行,而且不会产生其他影响。

  1. function Jedi(options) {
  2. options || (options = {});
  3. this.name = options.name || 'no name';
  4. }
  5.  
  6. Jedi.prototype.getName = function getName() {
  7. return this.name;
  8. };
  9.  
  10. Jedi.prototype.toString = function toString() {
  11. return 'Jedi - ' + this.getName();
  12. };

js 代码风格(2)的更多相关文章

  1. 大神的JS代码风格指南

    js代码风格指南:1.缩进使用空格,不要用制表符2.必须用分号3.暂时不用ES6(modules)例如export和import命令4.不鼓励(不禁止)水平对齐5.少用var 都应该使用const或者 ...

  2. Google HTML/CSS/JS代码风格指南

    JS版本参见:http://www.zhangxinxu.com/wordpress/2012/07/google-html-css-javascript-style-guides/ HTML/CSS ...

  3. JS代码风格自动规整工具Prettier

    问题背景 通常使用 ESLint做代码风格检查检查, 和部分代码质量检查. 但是使用ESLint在入库时候, 会产生很多的代码修正工作, 需要开发者一个一个的修改. 如果很多,并且时间紧迫,甚是尴尬. ...

  4. JS代码风格指南

    一.基本格式 缩进 建议每级4个空格,可以给编辑器设置tab = 4个空格,自动转换 分号 不要省略分号,防止ASI(自动插入分号)错误 行宽 每行代码不超过80个字符,过长应该用操作符手动断行 断行 ...

  5. highlight.js代码风格引入方法

    <link href="https://cdn.bootcss.com/highlight.js/9.15.10/styles/darcula.min.css" rel=&q ...

  6. js代码风格之链式结构

    <div class="box"> <ul class="menu"> <li class="level1"& ...

  7. [Js代码风格]浅析模块模式

    1.实例解释模块模式 简明扼要的说,经典的模块模式指的定义一个立即执行的匿名函数.在函数中定义私有函数和私有变量并且返回一个包含公共变量和公共函数作为属性和方法的匿名对象. var classicMo ...

  8. Django之代码风格

    1 代码风格 稍微关注一下下面这些代码标准风格指导规则将会对你大有益处,我们高度建议你通读词章,即便你此时可能正想跳过它. 1.1 让你的代码保持可读性的重要性 代码在读方面的重要性胜过写.一个代码块 ...

  9. .NET 项目代码风格要求

    原文:http://kb.cnblogs.com/page/179593/ 项目代码风格要求 PDF版下载:项目代码风格要求V1.0.pdf 代码风格没有正确与否,重要的是整齐划一,这是我拟的一份&l ...

随机推荐

  1. 实现toggleClass功能

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  2. android回调函数

    在我们进行android开发的时候,常常遇到一些回调函数,当中,我们最常常使用的回调就是,当我们对一个组件设置监听的时候,事实上就相对于设置的回调函数.比如: Button btn = (Button ...

  3. 微信小程序innerAudioContext接口

    voice:function(){ var word = this.data.word; var src = 'https://--/'+word['word']+'.mp3'; console.lo ...

  4. [Swift A] - DataSource 与 Delegate有啥区别?

    lukeluke     2012-05-22 07:46 是不是DATASOURCE,提供的是原来对象里并没有的数据,比如,共有几个ITEM啊, 而DELEGATE里,提供的是原来就有的数据,只不过 ...

  5. Spring Boot(二)Application events and listeners

    一.自定义监听器: 1.创建: META-INF/spring.factories 2.添加: org.springframework.context.ApplicationListener=com. ...

  6. shell中$0,$?,$!等的特殊使用方法

    变量说明: $$ Shell本身的PID(ProcessID) $! Shell最后执行的后台Process的PID $? 最后执行的命令的结束代码(返回值) $- 使用Set命令设定的Flag一览 ...

  7. 使用css3属性transition实现页面滚动

    <!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content ...

  8. C# EF更新当前实体报错 ObjectManager无法管理具有相同键值的多个对象

    原因: ObjectManager已经在跟踪此对象 更新实体前判断 if (db.Entry<T>(t).State != EntityState.Modified) db.Entry&l ...

  9. 自制MVC框架基础插件介绍

    本文介绍的基础插件不是实现BeforehandCommonAttribute或ProceedPlugin的postsharp插件,这些都是自定义的基础性的拦截,而且在项目中经常用到. 1). Comp ...

  10. 捅伊朗黑客PP — 后台登陆POST+错误回显 注入

    看了一个泰国政府的网站被伊朗的黑客挂页,上面写着“Your Box 0wn3z By Behrooz_Ice – Q7x -Sha2ow -Virangar -Ali_Eagle -iman_takt ...