最好用的javascript编码规范中文版.docx_第1页
最好用的javascript编码规范中文版.docx_第2页
最好用的javascript编码规范中文版.docx_第3页
最好用的javascript编码规范中文版.docx_第4页
最好用的javascript编码规范中文版.docx_第5页
已阅读5页,还剩27页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

最好用的javascript编码规范中文版类型 原始值: 存取直接作用于它自身。o stringo numbero booleano nullo undefined1. var foo = 1;2. var bar = foo;3.4. bar = 9;5.6. console.log(foo, bar); / = 1, 9 复杂类型: 存取时作用于它自身值的引用。o objecto arrayo function1. var foo = 1, 2;2. var bar = foo;3.4. bar0 = 9;5.6. console.log(foo0, bar0); / = 9, 9对象 使用直接量创建对象。1. / bad2. var item = new Object();3.4. / good5. var item = ; 不要使用保留字作为键名,它们在 IE8 下不工作。1. / bad2. var superman = 3. default: clark: kent ,4. private: true5. ;6.7. / good8. var superman = 9. defaults: clark: kent ,10. hidden: true11. ; 使用同义词替换需要使用的保留字。1. / bad2. var superman = 3. class: alien4. ;5.6. / bad7. var superman = 8. klass: alien9. ;10.11. / good12. var superman = 13. type: alien14. ;对象 使用直接量创建数组。1. / bad2. var items = new Array();3.4. / good5. var items = ; 向数组增加元素时使用 Array#push 来替代直接赋值。1. var someStack = ;2.3.4. / bad5. someStacksomeStack.length = abracadabra;6.7. / good8. someStack.push(abracadabra); 当你需要拷贝数组时,使用 Array#slice。1. var len = items.length;2. var itemsCopy = ;3. var i;4.5. / bad6. for (i = 0; i len; i+) 7. itemsCopyi = itemsi;8. 9.10. / good11. itemsCopy = items.slice(); 使用 Array#slice 将类数组对象转换成数组。1. function trigger() 2. var args = Atotype.slice.call(arguments);3. .4. 字符串 使用单引号 包裹字符串。1. / bad2. var name = Bob Parr;3.4. / good5. var name = Bob Parr;6.7. / bad8. var fullName = Bob + this.lastName;9.10. / good11. var fullName = Bob + this.lastName; 超过 100 个字符的字符串应该使用连接符写成多行。 注:若过度使用,通过连接符连接的长字符串可能会影响性能。1. / bad2. var errorMessage = 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.;3.4. / bad5. var errorMessage = This is a super long error that was thrown because 6. of Batman. When you stop to think about how Batman had anything to do 7. with this, you would get nowhere 8. fast.;9.10. / good11. var errorMessage = This is a super long error that was thrown because +12. of Batman. When you stop to think about how Batman had anything to do +13. with this, you would get nowhere fast.; 程序化生成的字符串使用 Array#join 连接而不是使用连接符。尤其是 IE 下1. var items;2. var messages;3. var length;4. var i;5.6. messages = 7. state: success,8. message: This one worked.9. , 10. state: success,11. message: This one worked as well.12. , 13. state: error,14. message: This one did not work.15. ;16.17. length = messages.length;18.19. / bad20. function inbox(messages) 21. items = ;22.23. for (i = 0; i length; i+) 24. items += + messagesi.message + ;25. 26.27. return items + ;28. 29.30. / good31. function inbox(messages) 32. items = ;33.34. for (i = 0; i length; i+) 35. / use direct assignment in this case because were micro-optimizing.36. itemsi = + messagesi.message + ;37. 38.39. return + items.join() + ;40. 函数 函数表达式:1. / 匿名函数表达式2. var anonymous = function() 3. return true;4. ;5.6. / 命名函数表达式7. var named = function named() 8. return true;9. ;10.11. / 立即调用的函数表达式(IIFE)12. (function () 13. console.log(Welcome to the Internet. Please follow me.);14. (); 永远不要在一个非函数代码块(if、while 等)中声明一个函数,把那个函数赋给一个变量。浏览器允许你这么做,但它们的解析表现不一致。 注: ECMA-262 把 块 定义为一组语句。函数声明不是语句。1. / bad2. if (currentUser) 3. function test() 4. console.log(Nope.);5. 6. 7.8. / good9. var test;10. if (currentUser) 11. test = function test() 12. console.log(Yup.);13. ;14. 永远不要把参数命名为 arguments。这将取代函数作用域内的 arguments 对象。1. / bad2. function nope(name, options, arguments) 3. / .stuff.4. 5.6. / good7. function yup(name, options, args) 8. / .stuff.9. 属性 使用 . 来访问对象的属性。1. var luke = 2. jedi: true,3. age: 284. ;5.6. / bad7. var isJedi = lukejedi;8.9. / good10. var isJedi = luke.jedi; 当通过变量访问属性时使用中括号 。1. var luke = 2. jedi: true,3. age: 284. ;5.6. function getProp(prop) 7. return lukeprop;8. 9.10. var isJedi = getProp(jedi);变量 总是使用 var 来声明变量。不这么做将导致产生全局变量。我们要避免污染全局命名空间。1. / bad2. superPower = new SuperPower();3.4. / good5. var superPower = new SuperPower();-使用 var 声明每一个变量。 这样做的好处是增加新变量将变的更加容易,而且你永远不用再担心调换错;跟,。1. / bad2. var items = getItems(),3. goSportsTeam = true,4. dragonball = z;5.6. / bad7. / (跟上面的代码比较一下,看看哪里错了)8. var items = getItems(),9. goSportsTeam = true;10. dragonball = z;11.12. / good13. var items = getItems();14. var goSportsTeam = true;15. var dragonball = z; 最后再声明未赋值的变量。当你需要引用前面的变量赋值时这将变的很有用。1. / bad2. var i, len, dragonball,3. items = getItems(),4. goSportsTeam = true;5.6. / bad7. var i;8. var items = getItems();9. var dragonball;10. var goSportsTeam = true;11. var len;12.13. / good14. var items = getItems();15. var goSportsTeam = true;16. var dragonball;17. var length;18. var i; 在作用域顶部声明变量。这将帮你避免变量声明提升相关的问题。1. / bad2. 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. / good18. 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. this.setFirstName(name);42.43. return true;44. 45.46. / good47. function () 48. var name;49.50. if (!arguments.length) 51. return false;52. 53.54. name = getName();55. this.setFirstName(name);56.57. return true;58. 提升 变量声明会提升至作用域顶部,但赋值不会。1. / 我们知道这样不能正常工作(假设这里没有名为 notDefined 的全局变量)2. function example() 3. console.log(notDefined); / = throws a ReferenceError4. 5.6. / 但由于变量声明提升的原因,在一个变量引用后再创建它的变量声明将可以正常工作。7. / 注:变量赋值为 true 不会提升。8. function example() 9. console.log(declaredButNotAssigned); / = undefined10. var declaredButNotAssigned = true;11. 12.13. / 解释器会把变量声明提升到作用域顶部,意味着我们的例子将被重写成:14. function example() 15. var declaredButNotAssigned;16. console.log(declaredButNotAssigned); / = undefined17. declaredButNotAssigned = true;18. 匿名函数表达式会提升它们的变量名,但不会提升函数的赋值。1. function example() 2. console.log(anonymous); / = undefined3.4. anonymous(); / = TypeError anonymous is not a function5.6. var anonymous = function () 7. console.log(anonymous function expression);8. ;9. 命名函数表达式会提升变量名,但不会提升函数名或函数体。1. function example() 2. console.log(named); / = undefined3.4. named(); / = TypeError named is not a function5.6. superPower(); / = ReferenceError superPower is not defined7.8. var named = function superPower() 9. console.log(Flying);10. ;11. 12.13. / 当函数名跟变量名一样时,表现也是如此。14. function example() 15. console.log(named); / = undefined16.17. named(); / = TypeError named is not a function18.19. var named = function named() 20. console.log(named);21. 22. 函数声明提升它们的名字和函数体。1. function example() 2. superPower(); / = Flying3.4. function superPower() 5. console.log(Flying);6. 7. 比较运算符&等号 优先使用 = 和 != 而不是 = 和 !=. 条件表达式例如 if 语句通过抽象方法 ToBoolean 强制计算它们的表达式并且总是遵守下面的规则:o 对象 被计算为 trueo Undefined 被计算为 falseo Null 被计算为 falseo 布尔值 被计算为 布尔的值o 数字 如果是 +0、-0 或 NaN 被计算为 false,否则为 trueo 字符串 如果是空字符串 被计算为 false,否则为 true1. if (0) 2. / true3. / 一个数组就是一个对象,对象被计算为 true4. 使用快捷方式。1. / bad2. if (name != ) 3. / .stuff.4. 5.6. / good7. if (name) 8. / .stuff.9. 10.11. / bad12. if (collection.length 0) 13. / .stuff.14. 15.16. / good17. if (collection.length) 18. / .stuff.19. 块 使用大括号包裹所有的多行代码块。1. / bad2. if (test)3. return false;4.5. / good6. if (test) return false;7.8. / good9. if (test) 10. return false;11. 12.13. / bad14. function () return false; 15.16. / good17. function () 18. return false;19. 如果通过 if 和 else 使用多行代码块,把 else 放在 if 代码块关闭括号的同一行。1. / bad2. if (test) 3. thing1();4. thing2();5. 6. else 7. thing3();8. 9.10. / good11. if (test) 12. thing1();13. thing2();14. else 15. thing3();16. 注释 使用 /* */ 作为多行注释。包含描述、指定所有参数和返回值的类型和值。1. / bad2. / make() returns a new element3. / based on the passed in tag name4. /5. / param String tag6. / return Element element7. function make(tag) 8.9. / .stuff.10.11. return element;12. 13.14. / good15. /*16. * make() returns a new element17. * based on the passed in tag name18. *19. * param String tag20. * return Element element21. */22. function make(tag) 23.24. / .stuff.25.26. return element;27. 使用 / 作为单行注释。在评论对象上面另起一行使用单行注释。在注释前插入空行。1. / bad2. var active = true; / is current tab3.4. / good5. / is current tab6. var active = true;7.8. / bad9. function getType() 10. console.log(fetching type.);11. / set the default type to no type12. var type = this.type | no type;13.14. return type;15. 16.17. / good18. function getType() 19. console.log(fetching type.);20.21. / set the default type to no type22. var type = this.type | no type;23.24. return type;25. 给注释增加FIXME或TODO的前缀可以帮助其他开发者快速了解这是一个需要复查的问题,或是给需要实现的功能提供一个解决方式。这将有别于常见的注释,因为它们是可操作的。使用FIXME-need to figurethisout或者TODO-need to implement。 使用/ FIXME:标注问题。1. function Calculator() 2.3. / FIXME: shouldnt use a global here4. total = 0;5.6. return this;7. 使用/ TODO:标注问题的解决方式。1. function Calculator() 2.3. / TODO: total should be configurable by an options param4. this.total = 0;5.6. return this;7. 空白 使用 2 个空格作为缩进。1. / bad2. function () 3. var name;4. 5.6. / bad7. function () 8. var name;9. 10.11. / good12. function () 13. var name;14. 在大括号前放一个空格。1. / bad2. function test()3. console.log(test);4. 5.6. / good7. function test() 8. console.log(test);9. 10.11. / bad12. dog.set(attr,13. age: 1 year,14. breed: Bernese Mountain Dog15. );16.17. / good18. dog.set(attr, 19. age: 1 year,20. breed: Bernese Mountain Dog21. ); 在控制语句(if、while 等)的小括号前放一个空格。在函数调用及声明中,不在函数的参数列表前加空格。1. / bad2. if(isJedi) 3. fight ();4. 5.6. / good7. if (isJedi) 8. fight();9. 10.11. / bad12. function fight () 13. console.log (Swooosh!);14. 15.16. / good17. function fight() 18. console.log(Swooosh!);19. 使用空格把运算符隔开。1. / bad2. var x=y+5;3.4. / good5. var x = y + 5; 在文件末尾插入一个空行。1. / bad2. (function (global) 3. / .stuff.4. )(this);5. / bad6. (function (global) 7. / .stuff.8. )(this);9. 10. / good11. (function (global) 12. / .stuff.13. )(this); 在使用长方法链时进行缩进。使用前面的点.强调这是方法调用而不是新语句。1. / bad2. $(#items).find(.selected).highlight().end().find(.open).updateCount();3.4. / bad5. $(#items).6. find(.selected).7. highlight().8. end().9. find(.open).10. updateCount();11.12. / good13. $(#items)14. .find(.selected)15. .highlight()16. .end()17. .find(.open)18. .updateCount();19.20. / bad21. var leds = stage.selectAll(.led).data(data).enter().append(svg:svg).classed(led, true)22. .attr(width, (radius + margin) * 2).append(svg:g)23. .attr(transform, translate( + (radius + margin) + , + (radius + margin) + )24. .call(tron.led);25.26. / good27. var leds = stage.selectAll(.led)28. .data(data)29. .enter().append(svg:svg)30. .classed(led, true)31. .attr(width, (radius + margin) * 2)32. .append(svg:g)33. .attr(transform, translate( + (radius + margin) + , + (radius + margin) + )34. .call(tron.led); 在块末和新语句前插入空行。1. / bad2. if (foo) 3. return bar;4. 5. return baz;6.7. / good8. if (foo) 9. return bar;10. 11.12. return baz;13.14. / bad15. var obj = 16. foo: function () 17. ,18. bar: function () 19. 20. ;21. return obj;22.23. / good24. var obj = 25. foo: function () 26. ,27.28. bar: function () 29. 30. ;31.32. return obj;逗号 行首逗号: 不需要。1. / bad2. var story = 3. once4. , upon5. , aTime6. ;7.8. / good9. var story = 10. once,11. upon,12. aTime13. ;14.15. / bad16. var hero = 17. firstName: Bob18. , lastName: Parr19. , heroName: Mr. Incredible20. , superPower: strength21. ;22.23. / good24. var hero = 25. firstName: Bob,26. lastName: Parr,27. heroName: Mr. Incredible,28. superPower: strength29. ; 额外的行末逗号:不需要。这样做会在 IE6/7 和 IE9 怪异模式下引起问题。同样,多余的逗号在某些 ES3 的实现里会增加数组的长度。1. / bad2. var hero = 3. firstName: Kevin,4. lastName: Flynn,5. ;6.7. var heroes = 8. Batman,9. Superman,10. ;11.12. / good13. var hero = 14. firstName: Kevin,15. lastName: Flynn16. ;17.18. var heroes = 19. Batman,20. Superman21. ;分号 使用分号。1. / bad2. (function () 3. var name = Skywalker4. return name5. )()6.7. / good8. (function () 9. var name = Skywalker;10. return name;11. )();12.13. / good (防止函数在两个 IIFE 合并时被当成一个参数14. ;(function () 15. var name = Skywalker;16. return name;17. )();类型转换 在语句开始时执行类型转换。 字符串:1. / = this.reviewScore = 9;2.3. / bad4. var totalScore = this.reviewScore + ;5.6. / good7. var totalScore = + this.reviewScore;8.9. / bad10. var totalScore = + this.reviewScore + total score;11.12. / good13. var totalScore = this.reviewScore + total score; 使用 parseInt 转换数字时总是带上类型转换的基数。1. var inputValue = 4;2.3. / bad4. var val = new Number(inputValue);5.6. / bad7. var val = +inputValue;8.9. / bad10. var val = inputValue 0;11.12. / bad13. var val = parseInt(inputValue);14.15. / good16. var val = Number(inputValue);17.18. / good19. var val = parseInt(inputValue, 10); 如果因为某些原因 parseInt 成为你所做的事的瓶颈而需要使用位操作解决性能问题时,留个注释说清楚原因和你的目的。1. / good2. /*3. * parseInt was the reason my code was slow.4. * Bitshifting the String to coerce it to a5. * Number made it a lot faster.6. */7. var val = inputValue 0; 注: 小心使用位操作运算符。数字会被当成 64 位值,但是位操作运算符总是返回 32 位的整数(source)。位操作处理大于 32 位的整数值时还会导致意料之外的行为。讨论。最大的 32 位整数是 2,147,483,647:1. 2147483647 0 /= 21474836472. 2147483648 0 /= -21474836483. 2147483649 0 /= -2147483647 布尔:1. var age = 0;2.3. / bad4. var hasAge = new Boolean(age);5.6. / good7. var hasAge = Boolean(age);8.9. / good10. var hasAge = !age;命名规则 避免单字母命名。命名应具备描述性。1. / bad2. function q() 3. / .stuff.4. 5.6. / good7. function query() 8. / .stuff.9. 使用驼峰式命名对象、函数和实例。1. / bad2. var OBJEcttsssss = ;3. var this_is_my_object = ;4. var o = ;5. function c() 6.7. / good8. var thisIsMyObject = ;9. function thisIsMyFunction() 使用帕斯卡式命名构造函数或类。1. / bad2. function user(options) 3. = ;4. 5.6. var bad = new user(7. name: nope8. );9.10. / good11. function User(options) 12. = ;13. 14.15. var good = new User(16. name: yup17. ); 不要使用下划线前/后缀。为什么?JavaScript 并没有私有属性或私有方法的概念。虽然使用下划线是表示私有的一种共识,但实际上这些属性是完全公开的,它本身就是你公共接口的一部分。这种习惯或许会导致开发者错误的认为改动它不会造成破坏或者不需要去测试。长话短说:如果你想要某处为私有,它必须不能是显式提出的。1. / bad2. this._firstName_ = Panda;3. this.firstName_ = Panda;4. this._firstName = Panda;5.6. / good7. this.firstName = Panda; 不要保存 this 的引用。使用 Function#bind。1. / bad2. function () 3. var self = this;4. return function () 5. console.log(self);6. ;7. 8.9. / bad10. function () 11. var that = this;12. return function () 13. console.log(that);14. ;15. 16.17. / bad18. function () 19. var _this = this;20. return function () 21. console.log(_this);22. ;23. 24.25. / good26. function () 27. return function () 28. console.log(this);29. .bind(this);30. 给函数命名。这在做堆栈轨迹时很有帮助。1. / bad2. var log = function (msg) 3. console.log(msg);4. ;5.6. / good7. var log = function log(msg) 8. console.log(msg);9. ; 注: IE8 及以下版本对命名函数表达式的处理有些怪异。 如果你的文件导出一个类,你的文件名应该与类名完全相同。1. / file contents2. class CheckBox 3. / .4. 5. module.exports = CheckBox;6.7. / in some other file8. / bad9. var CheckBox = require(./checkBox);10.11. / bad12. var CheckBox = require(./check_box);13.14. / g

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论