36. License

最后更新于:2022-04-01 21:13:19

(The MIT License) Copyright (c) 2014 Airbnb Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # };
';

35. Contributors

最后更新于:2022-04-01 21:13:17

* [View Contributors](https://github.com/airbnb/javascript/graphs/contributors)
';

34. 一起来讨论Javascript

最后更新于:2022-04-01 21:13:14

* Find us on [gitter](https://gitter.im/airbnb/javascript).
';

33. JavaScript 编码规范说明

最后更新于:2022-04-01 21:13:12

* [Reference](https://github.com/airbnb/javascript/wiki/The-JavaScript-Style-Guide-Guide)
';

32. 翻译

最后更新于:2022-04-01 21:13:10

This style guide is also available in other languages: * [![br](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Brazil.png)](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2015-07-13_55a374884dbcd.png) **Brazilian Portuguese**: [armoucar/javascript-style-guide](https://github.com/armoucar/javascript-style-guide) * [![bg](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Bulgaria.png)](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2015-07-13_55a37496d7f8e.png) **Bulgarian**: [borislavvv/javascript](https://github.com/borislavvv/javascript) * [![ca](https://raw.githubusercontent.com/fpmweb/javascript-style-guide/master/img/catala.png)](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2015-07-13_55a3749c32616.png) **Catalan**: [fpmweb/javascript-style-guide](https://github.com/fpmweb/javascript-style-guide) * [![tw](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Taiwan.png)](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2015-07-13_55a374c25686f.png) **Chinese(Traditional)**: [jigsawye/javascript](https://github.com/jigsawye/javascript) * [![cn](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/China.png)](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2015-07-13_55a374cb5075e.png) **Chinese(Simplified)**: [yuche/javascript](https://github.com/yuche/javascript) * [![fr](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/France.png)](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2015-07-13_55a374d49eb78.png) **French**: [nmussy/javascript-style-guide](https://github.com/nmussy/javascript-style-guide) * [![de](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Germany.png)](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2015-07-13_55a374d97275d.png) **German**: [timofurrer/javascript-style-guide](https://github.com/timofurrer/javascript-style-guide) * [![it](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Italy.png)](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2015-07-13_55a374ed0a3ba.png) **Italian**: [sinkswim/javascript-style-guide](https://github.com/sinkswim/javascript-style-guide) * [![jp](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Japan.png)](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2015-07-13_55a374f5b0d3c.png) **Japanese**: [mitsuruog/javacript-style-guide](https://github.com/mitsuruog/javacript-style-guide) * [![kr](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/South-Korea.png)](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2015-07-13_55a374fe9cfa2.png) **Korean**: [tipjs/javascript-style-guide](https://github.com/tipjs/javascript-style-guide) * [![pl](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Poland.png)](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2015-07-13_55a3750b89a64.png) **Polish**: [mjurczyk/javascript](https://github.com/mjurczyk/javascript) * [![ru](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Russia.png)](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2015-07-13_55a37513132ee.png) **Russian**: [uprock/javascript](https://github.com/uprock/javascript) * [![es](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Spain.png)](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2015-07-13_55a37518935c0.png) **Spanish**: [paolocarrasco/javascript-style-guide](https://github.com/paolocarrasco/javascript-style-guide) * [![th](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Thailand.png)](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2015-07-13_55a3751d9b5f4.png) **Thai**: [lvarayut/javascript-style-guide](https://github.com/lvarayut/javascript-style-guide)
';

31. 使用人群

最后更新于:2022-04-01 21:13:08

This is a list of organizations that are using this style guide. Send us a pull request or open an issue and we'll add you to the list. * **Aan Zee**: [AanZee/javascript](https://github.com/AanZee/javascript) * **Adult Swim**: [adult-swim/javascript](https://github.com/adult-swim/javascript) * **Airbnb**: [airbnb/javascript](https://github.com/airbnb/javascript) * **American Insitutes for Research**: [AIRAST/javascript](https://github.com/AIRAST/javascript) * **Apartmint**: [apartmint/javascript](https://github.com/apartmint/javascript) * **Avalara**: [avalara/javascript](https://github.com/avalara/javascript) * **Billabong**: [billabong/javascript](https://github.com/billabong/javascript) * **Compass Learning**: [compasslearning/javascript-style-guide](https://github.com/compasslearning/javascript-style-guide) * **DailyMotion**: [dailymotion/javascript](https://github.com/dailymotion/javascript) * **Digitpaint** [digitpaint/javascript](https://github.com/digitpaint/javascript) * **Evernote**: [evernote/javascript-style-guide](https://github.com/evernote/javascript-style-guide) * **ExactTarget**: [ExactTarget/javascript](https://github.com/ExactTarget/javascript) * **Expensify** [Expensify/Style-Guide](https://github.com/Expensify/Style-Guide/blob/master/javascript.md) * **Flexberry**: [Flexberry/javascript-style-guide](https://github.com/Flexberry/javascript-style-guide) * **Gawker Media**: [gawkermedia/javascript](https://github.com/gawkermedia/javascript) * **GeneralElectric**: [GeneralElectric/javascript](https://github.com/GeneralElectric/javascript) * **GoodData**: [gooddata/gdc-js-style](https://github.com/gooddata/gdc-js-style) * **Grooveshark**: [grooveshark/javascript](https://github.com/grooveshark/javascript) * **How About We**: [howaboutwe/javascript](https://github.com/howaboutwe/javascript) * **InfoJobs**: [InfoJobs/JavaScript-Style-Guide](https://github.com/InfoJobs/JavaScript-Style-Guide) * **Intent Media**: [intentmedia/javascript](https://github.com/intentmedia/javascript) * **Jam3**: [Jam3/Javascript-Code-Conventions](https://github.com/Jam3/Javascript-Code-Conventions) * **JSSolutions**: [JSSolutions/javascript](https://github.com/JSSolutions/javascript) * **Kinetica Solutions**: [kinetica/javascript](https://github.com/kinetica/javascript) * **Mighty Spring**: [mightyspring/javascript](https://github.com/mightyspring/javascript) * **MinnPost**: [MinnPost/javascript](https://github.com/MinnPost/javascript) * **ModCloth**: [modcloth/javascript](https://github.com/modcloth/javascript) * **Money Advice Service**: [moneyadviceservice/javascript](https://github.com/moneyadviceservice/javascript) * **Muber**: [muber/javascript](https://github.com/muber/javascript) * **National Geographic**: [natgeo/javascript](https://github.com/natgeo/javascript) * **National Park Service**: [nationalparkservice/javascript](https://github.com/nationalparkservice/javascript) * **Nimbl3**: [nimbl3/javascript](https://github.com/nimbl3/javascript) * **Orion Health**: [orionhealth/javascript](https://github.com/orionhealth/javascript) * **Peerby**: [Peerby/javascript](https://github.com/Peerby/javascript) * **Razorfish**: [razorfish/javascript-style-guide](https://github.com/razorfish/javascript-style-guide) * **reddit**: [reddit/styleguide/javascript](https://github.com/reddit/styleguide/tree/master/javascript) * **REI**: [reidev/js-style-guide](https://github.com/reidev/js-style-guide) * **Ripple**: [ripple/javascript-style-guide](https://github.com/ripple/javascript-style-guide) * **SeekingAlpha**: [seekingalpha/javascript-style-guide](https://github.com/seekingalpha/javascript-style-guide) * **Shutterfly**: [shutterfly/javascript](https://github.com/shutterfly/javascript) * **StudentSphere**: [studentsphere/javascript](https://github.com/studentsphere/javascript) * **Target**: [target/javascript](https://github.com/target/javascript) * **TheLadders**: [TheLadders/javascript](https://github.com/TheLadders/javascript) * **T4R Technology**: [T4R-Technology/javascript](https://github.com/T4R-Technology/javascript) * **Userify**: [userify/javascript](https://github.com/userify/javascript) * **VoxFeed**: [VoxFeed/javascript-style-guide](https://github.com/VoxFeed/javascript-style-guide) * **Weggo**: [Weggo/javascript](https://github.com/Weggo/javascript) * **Zillow**: [zillow/javascript](https://github.com/zillow/javascript) * **ZocDoc**: [ZocDoc/javascript](https://github.com/ZocDoc/javascript)
';

30. 资源

最后更新于:2022-04-01 21:13:05

**Learning ES6** * [Draft ECMA 2015 (ES6) Spec](https://people.mozilla.org/~jorendorff/es6-draft.html) * [ExploringJS](http://exploringjs.com/) * [ES6 Compatibility Table](https://kangax.github.io/compat-table/es6/) * [Comprehensive Overview of ES6 Features](http://es6-features.org/) **Read This** * [Annotated ECMAScript 5.1](http://es5.github.com/) **Tools** * Code Style Linters * [ESlint](http://eslint.org/) - [Airbnb Style .eslintrc](https://github.com/airbnb/javascript/blob/master/linters/.eslintrc) * [JSHint](http://www.jshint.com/) - [Airbnb Style .jshintrc](https://github.com/airbnb/javascript/blob/master/linters/jshintrc) * [JSCS](https://github.com/jscs-dev/node-jscs) - [Airbnb Style Preset](https://github.com/jscs-dev/node-jscs/blob/master/presets/airbnb.json) **Other Styleguides** * [Google JavaScript Style Guide](http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml) * [jQuery Core Style Guidelines](http://docs.jquery.com/JQuery_Core_Style_Guidelines) * [Principles of Writing Consistent, Idiomatic JavaScript](https://github.com/rwldrn/idiomatic.js/) **Other Styles** * [Naming this in nested functions](https://gist.github.com/4135065) - Christian Johansen * [Conditional Callbacks](https://github.com/airbnb/javascript/issues/52) - Ross Allen * [Popular JavaScript Coding Conventions on Github](http://sideeffect.kr/popularconvention/#javascript) - JeongHoon Byun * [Multiple var statements in JavaScript, not superfluous](http://benalman.com/news/2012/05/multiple-var-statements-javascript/) - Ben Alman **Further Reading** * [Understanding JavaScript Closures](http://javascriptweblog.wordpress.com/2010/10/25/understanding-javascript-closures/) - Angus Croll * [Basic JavaScript for the impatient programmer](http://www.2ality.com/2013/06/basic-javascript.html) - Dr. Axel Rauschmayer * [You Might Not Need jQuery](http://youmightnotneedjquery.com/) - Zack Bloom & Adam Schwartz * [ES6 Features](https://github.com/lukehoban/es6features) - Luke Hoban * [Frontend Guidelines](https://github.com/bendc/frontend-guidelines) - Benjamin De Cock **Books** * [JavaScript: The Good Parts](http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742) - Douglas Crockford * [JavaScript Patterns](http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752) - Stoyan Stefanov * [Pro JavaScript Design Patterns](http://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X) - Ross Harmes and Dustin Diaz * [High Performance Web Sites: Essential Knowledge for Front-End Engineers](http://www.amazon.com/High-Performance-Web-Sites-Essential/dp/0596529309) - Steve Souders * [Maintainable JavaScript](http://www.amazon.com/Maintainable-JavaScript-Nicholas-C-Zakas/dp/1449327680) - Nicholas C. Zakas * [JavaScript Web Applications](http://www.amazon.com/JavaScript-Web-Applications-Alex-MacCaw/dp/144930351X) - Alex MacCaw * [Pro JavaScript Techniques](http://www.amazon.com/Pro-JavaScript-Techniques-John-Resig/dp/1590597273) - John Resig * [Smashing Node.js: JavaScript Everywhere](http://www.amazon.com/Smashing-Node-js-JavaScript-Everywhere-Magazine/dp/1119962595) - Guillermo Rauch * [Secrets of the JavaScript Ninja](http://www.amazon.com/Secrets-JavaScript-Ninja-John-Resig/dp/193398869X) - John Resig and Bear Bibeault * [Human JavaScript](http://humanjavascript.com/) - Henrik Joreteg * [Superhero.js](http://superherojs.com/) - Kim Joar Bekkelund, Mads Mobæk, & Olav Bjorkoy * [JSBooks](http://jsbooks.revolunet.com/) - Julien Bouquillon * [Third Party JavaScript](http://manning.com/vinegar/) - Ben Vinegar and Anton Kovalyov * [Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript](http://amzn.com/0321812182) - David Herman * [Eloquent JavaScript](http://eloquentjavascript.net/) - Marijn Haverbeke **Blogs** * [DailyJS](http://dailyjs.com/) * [JavaScript Weekly](http://javascriptweekly.com/) * [JavaScript, JavaScript...](http://javascriptweblog.wordpress.com/) * [Bocoup Weblog](http://weblog.bocoup.com/) * [Adequately Good](http://www.adequatelygood.com/) * [NCZOnline](http://www.nczonline.net/) * [Perfection Kills](http://perfectionkills.com/) * [Ben Alman](http://benalman.com/) * [Dmitry Baranovskiy](http://dmitry.baranovskiy.com/) * [Dustin Diaz](http://dustindiaz.com/) * [nettuts](http://net.tutsplus.com/?s=javascript) **Podcasts** * [JavaScript Jabber](http://devchat.tv/js-jabber/)
';

29. 性能

最后更新于:2022-04-01 21:13:03

* [On Layout & Web Performance](http://kellegous.com/j/2013/01/26/layout-performance/) * [String vs Array Concat](http://jsperf.com/string-vs-array-concat/2) * [Try/Catch Cost In a Loop](http://jsperf.com/try-catch-in-loop-cost) * [Bang Function](http://jsperf.com/bang-function) * [jQuery Find vs Context, Selector](http://jsperf.com/jquery-find-vs-context-sel/13) * [innerHTML vs textContent for script text](http://jsperf.com/innerhtml-vs-textcontent-for-script-text) * [Long String Concatenation](http://jsperf.com/ya-string-concat) * Loading...
';

28. 测试

最后更新于:2022-04-01 21:13:01

* [28.1](https://github.com/yuche/javascript#28.1) **Yup.** ~~~ function() { return true; } ~~~
';

27. ECMAScript 6 编码规范

最后更新于:2022-04-01 21:12:58

* [27.1](https://github.com/yuche/javascript#27.1) 以下是链接到 ES6 的各个特性的列表。 1. [Arrow Functions](https://github.com/yuche/javascript#arrow-functions) 2. [Classes](https://github.com/yuche/javascript#constructors) 3. [Object Shorthand](https://github.com/yuche/javascript#es6-object-shorthand) 4. [Object Concise](https://github.com/yuche/javascript#es6-object-concise) 5. [Object Computed Properties](https://github.com/yuche/javascript#es6-computed-properties) 6. [Template Strings](https://github.com/yuche/javascript#es6-template-literals) 7. [Destructuring](https://github.com/yuche/javascript#destructuring) 8. [Default Parameters](https://github.com/yuche/javascript#es6-default-parameters) 9. [Rest](https://github.com/yuche/javascript#es6-rest) 10. [Array Spreads](https://github.com/yuche/javascript#es6-array-spreads) 11. [Let and Const](https://github.com/yuche/javascript#references) 12. [Iterators and Generators](https://github.com/yuche/javascript#iterators-and-generators) 13. [Modules](https://github.com/yuche/javascript#modules)
';

26. ECMAScript 5 兼容性

最后更新于:2022-04-01 21:12:56

* [26.1](https://github.com/yuche/javascript#26.1) 参考 [Kangax](https://twitter.com/kangax/) 的 ES5 [兼容性](http://kangax.github.com/es5-compat-table/).
';

25. jQuery

最后更新于:2022-04-01 21:12:54

* [25.1](https://github.com/yuche/javascript#25.1) 使用 `$` 作为存储 jQuery 对象的变量名前缀。 ~~~ // bad const sidebar = $('.sidebar'); // good const $sidebar = $('.sidebar'); ~~~ * [25.2](https://github.com/yuche/javascript#25.2) 缓存 jQuery 查询。 ~~~ // bad function setSidebar() { $('.sidebar').hide(); // ...stuff... $('.sidebar').css({ 'background-color': 'pink' }); } // good function setSidebar() { const $sidebar = $('.sidebar'); $sidebar.hide(); // ...stuff... $sidebar.css({ 'background-color': 'pink' }); } ~~~ * [25.3](https://github.com/yuche/javascript#25.3) 对 DOM 查询使用层叠 `$('.sidebar ul')` 或 父元素 > 子元素 `$('.sidebar > ul')`。 [jsPerf](http://jsperf.com/jquery-find-vs-context-sel/16) * [25.4](https://github.com/yuche/javascript#25.4) 对有作用域的 jQuery 对象查询使用 `find`。 ~~~ // bad $('ul', '.sidebar').hide(); // bad $('.sidebar').find('ul').hide(); // good $('.sidebar ul').hide(); // good $('.sidebar > ul').hide(); // good $sidebar.find('ul').hide(); ~~~
';

24. 事件

最后更新于:2022-04-01 21:12:51

[24.1](https://github.com/yuche/javascript#24.1) 当给时间附加数据时(无论是 DOM 事件还是私有事件),传入一个哈希而不是原始值。这样可以让后面的贡献者增加更多数据到事件数据而无需找出并更新事件的每一个处理器。例如,不好的写法: ~~~ // bad $(this).trigger('listingUpdated', listing.id); ... $(this).on('listingUpdated', function(e, listingId) { // do something with listingId }); ~~~ 更好的写法: ~~~ // good $(this).trigger('listingUpdated', { listingId : listing.id }); ... $(this).on('listingUpdated', function(e, data) { // do something with data.listingId }); ~~~
';

23. 存取器

最后更新于:2022-04-01 21:12:49

* [23.1](https://github.com/yuche/javascript#23.1) 属性的存取函数不是必须的。 * [23.2](https://github.com/yuche/javascript#23.2) 如果你需要存取函数时使用 `getVal()` 和 `setVal('hello')`。 ~~~ // bad dragon.age(); // good dragon.getAge(); // bad dragon.age(25); // good dragon.setAge(25); ~~~ * [23.3](https://github.com/yuche/javascript#23.3) 如果属性是布尔值,使用 `isVal()` 或 `hasVal()`。 ~~~ // bad if (!dragon.age()) { return false; } // good if (!dragon.hasAge()) { return false; } ~~~ * [23.4](https://github.com/yuche/javascript#23.4) 创建 `get()` 和 `set()` 函数是可以的,但要保持一致。 ~~~ class Jedi { constructor(options = {}) { const lightsaber = options.lightsaber || 'blue'; this.set('lightsaber', lightsaber); } set(key, val) { this[key] = val; } get(key) { return this[key]; } } ~~~
';

22. 命名规则

最后更新于:2022-04-01 21:12:47

* [22.1](https://github.com/yuche/javascript#22.1) 避免单字母命名。命名应具备描述性。 ~~~ // bad function q() { // ...stuff... } // good function query() { // ..stuff.. } ~~~ * [22.2](https://github.com/yuche/javascript#22.2) 使用驼峰式命名对象、函数和实例。 ~~~ // bad const OBJEcttsssss = {}; const this_is_my_object = {}; function c() {} // good const thisIsMyObject = {}; function thisIsMyFunction() {} ~~~ * [22.3](https://github.com/yuche/javascript#22.3) 使用帕斯卡式命名构造函数或类。 ~~~ // bad function user(options) { this.name = options.name; } const bad = new user({ name: 'nope', }); // good class User { constructor(options) { this.name = options.name; } } const good = new User({ name: 'yup', }); ~~~ * [22.4](https://github.com/yuche/javascript#22.4) 使用下划线 `_` 开头命名私有属性。 ~~~ // bad this.__firstName__ = 'Panda'; this.firstName_ = 'Panda'; // good this._firstName = 'Panda'; ~~~ * [22.5](https://github.com/yuche/javascript#22.5) 别保存 `this` 的引用。使用箭头函数或 Function#bind。 ~~~ // bad function foo() { const self = this; return function() { console.log(self); }; } // bad function foo() { const that = this; return function() { console.log(that); }; } // good function foo() { return () => { console.log(this); }; } ~~~ * [22.6](https://github.com/yuche/javascript#22.6) 如果你的文件只输出一个类,那你的文件名必须和类名完全保持一致。 ~~~ // file contents class CheckBox { // ... } export default CheckBox; // in some other file // bad import CheckBox from './checkBox'; // bad import CheckBox from './check_box'; // good import CheckBox from './CheckBox'; ~~~ * [22.7](https://github.com/yuche/javascript#22.7) 当你导出默认的函数时使用驼峰式命名。你的文件名必须和函数名完全保持一致。 ~~~ function makeStyleGuide() { } export default makeStyleGuide; ~~~ * [22.8](https://github.com/yuche/javascript#22.8) 当你导出单例、函数库、空对象时使用帕斯卡式命名。 ~~~ const AirbnbStyleGuide = { es6: { } }; export default AirbnbStyleGuide; ~~~
';

21. 类型转换

最后更新于:2022-04-01 21:12:45

* [21.1](https://github.com/yuche/javascript#21.1) 在语句开始时执行类型转换。 * [21.2](https://github.com/yuche/javascript#21.2) 字符串: ~~~ // => this.reviewScore = 9; // bad const totalScore = this.reviewScore + ''; // good const totalScore = String(this.reviewScore); ~~~ * [21.3](https://github.com/yuche/javascript#21.3) 对数字使用 `parseInt` 转换,并带上类型转换的基数。 ~~~ const inputValue = '4'; // bad const val = new Number(inputValue); // bad const val = +inputValue; // bad const val = inputValue >> 0; // bad const val = parseInt(inputValue); // good const val = Number(inputValue); // good const val = parseInt(inputValue, 10); ~~~ * [21.4](https://github.com/yuche/javascript#21.4) 如果因为某些原因 parseInt 成为你所做的事的瓶颈而需要使用位操作解决[性能问题](http://jsperf.com/coercion-vs-casting/3)时,留个注释说清楚原因和你的目的。 ~~~ // good /** * 使用 parseInt 导致我的程序变慢, * 改成使用位操作转换数字快多了。 */ const val = inputValue >> 0; ~~~ * [21.5](https://github.com/yuche/javascript#21.5) **注:** 小心使用位操作运算符。数字会被当成 [64 位值](http://es5.github.io/#x4.3.19),但是位操作运算符总是返回 32 位的整数([参考](http://es5.github.io/#x11.7))。位操作处理大于 32 位的整数值时还会导致意料之外的行为。[关于这个问题的讨论](https://github.com/airbnb/javascript/issues/109)。最大的 32 位整数是 2,147,483,647: ~~~ 2147483647 >> 0 //=> 2147483647 2147483648 >> 0 //=> -2147483648 2147483649 >> 0 //=> -2147483647 ~~~ * [21.6](https://github.com/yuche/javascript#21.6) 布尔: ~~~ const age = 0; // bad const hasAge = new Boolean(age); // good const hasAge = Boolean(age); // good const hasAge = !!age; ~~~
';

20. 分号

最后更新于:2022-04-01 21:12:42

[20.1](https://github.com/yuche/javascript#20.1) **使用分号** ~~~ // bad (function() { const name = 'Skywalker' return name })() // good (() => { const name = 'Skywalker'; return name; })(); // good (防止函数在两个 IIFE 合并时被当成一个参数) ;(() => { const name = 'Skywalker'; return name; })(); ~~~
';

19. 逗号

最后更新于:2022-04-01 21:12:40

* [19.1](https://github.com/yuche/javascript#19.1) 行首逗号:**不需要**。 ~~~ // bad const story = [ once , upon , aTime ]; // good const story = [ once, upon, aTime, ]; // bad const hero = { firstName: 'Ada' , lastName: 'Lovelace' , birthYear: 1815 , superPower: 'computers' }; // good const hero = { firstName: 'Ada', lastName: 'Lovelace', birthYear: 1815, superPower: 'computers', }; ~~~ * [19.2](https://github.com/yuche/javascript#19.2) 增加结尾的逗号: **需要**。 > 为什么? 这会让 git diffs 更干净。另外,像 babel 这样的转译器会移除结尾多余的逗号,也就是说你不必担心老旧浏览器的[尾逗号问题](https://github.com/yuche/javascript/blob/master/es5/README.md#commas)。 ~~~ // bad - git diff without trailing comma const hero = { firstName: 'Florence', - lastName: 'Nightingale' + lastName: 'Nightingale', + inventorOf: ['coxcomb graph', 'modern nursing'] } // good - git diff with trailing comma const hero = { firstName: 'Florence', lastName: 'Nightingale', + inventorOf: ['coxcomb chart', 'modern nursing'], } // bad const hero = { firstName: 'Dana', lastName: 'Scully' }; const heroes = [ 'Batman', 'Superman' ]; // good const hero = { firstName: 'Dana', lastName: 'Scully', }; const heroes = [ 'Batman', 'Superman', ]; ~~~
';

18. 空白

最后更新于:2022-04-01 21:12:38

* [18.1](https://github.com/yuche/javascript#18.1) 使用 2 个空格作为缩进。 ~~~ // bad function() { ∙∙∙∙const name; } // bad function() { ∙const name; } // good function() { ∙∙const name; } ~~~ * [18.2](https://github.com/yuche/javascript#18.2) 在花括号前放一个空格。 ~~~ // bad function test(){ console.log('test'); } // good function test() { console.log('test'); } // bad dog.set('attr',{ age: '1 year', breed: 'Bernese Mountain Dog', }); // good dog.set('attr', { age: '1 year', breed: 'Bernese Mountain Dog', }); ~~~ * [18.3](https://github.com/yuche/javascript#18.3) 在控制语句(`if`、`while` 等)的小括号前放一个空格。在函数调用及声明中,不在函数的参数列表前加空格。 ~~~ // bad if(isJedi) { fight (); } // good if (isJedi) { fight(); } // bad function fight () { console.log ('Swooosh!'); } // good function fight() { console.log('Swooosh!'); } ~~~ * [18.4](https://github.com/yuche/javascript#18.4) 使用空格把运算符隔开。 ~~~ // bad const x=y+5; // good const x = y + 5; ~~~ * [18.5](https://github.com/yuche/javascript#18.5) 在文件末尾插入一个空行。 ~~~ // bad (function(global) { // ...stuff... })(this); ~~~ ~~~ // bad (function(global) { // ...stuff... })(this);↵ ↵ ~~~ ~~~ // good (function(global) { // ...stuff... })(this);↵ ~~~ * [18.5](https://github.com/yuche/javascript#18.5) 在使用长方法链时进行缩进。使用前面的点 `.` 强调这是方法调用而不是新语句。 ~~~ // bad $('#items').find('.selected').highlight().end().find('.open').updateCount(); // bad $('#items'). find('.selected'). highlight(). end(). find('.open'). updateCount(); // good $('#items') .find('.selected') .highlight() .end() .find('.open') .updateCount(); // bad const leds = stage.selectAll('.led').data(data).enter().append('svg:svg').class('led', true) .attr('width', (radius + margin) * 2).append('svg:g') .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')') .call(tron.led); // good const leds = stage.selectAll('.led') .data(data) .enter().append('svg:svg') .classed('led', true) .attr('width', (radius + margin) * 2) .append('svg:g') .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')') .call(tron.led); ~~~ * [18.6](https://github.com/yuche/javascript#18.6) 在块末和新语句前插入空行。 ~~~ // bad if (foo) { return bar; } return baz; // good if (foo) { return bar; } return baz; // bad const obj = { foo() { }, bar() { }, }; return obj; // good const obj = { foo() { }, bar() { }, }; return obj; ~~~
';

17. 注释

最后更新于:2022-04-01 21:12:36

* [17.1](https://github.com/yuche/javascript#17.1) 使用 `/** ... */` 作为多行注释。包含描述、指定所有参数和返回值的类型和值。 ~~~ // bad // make() returns a new element // based on the passed in tag name // // @param {String} tag // @return {Element} element function 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; } ~~~ * [17.2](https://github.com/yuche/javascript#17.2) 使用 `//` 作为单行注释。在评论对象上面另起一行使用单行注释。在注释前插入空行。 ~~~ // bad const active = true; // is current tab // good // is current tab const active = true; // bad function getType() { console.log('fetching type...'); // set the default type to 'no type' const type = this._type || 'no type'; return type; } // good function getType() { console.log('fetching type...'); // set the default type to 'no type' const type = this._type || 'no type'; return type; } ~~~ * [17.3](https://github.com/yuche/javascript#17.3) 给注释增加 `FIXME` 或 `TODO` 的前缀可以帮助其他开发者快速了解这是一个需要复查的问题,或是给需要实现的功能提供一个解决方式。这将有别于常见的注释,因为它们是可操作的。使用`FIXME -- need to figure this out` 或者 `TODO -- need to implement`。 * [17.4](https://github.com/yuche/javascript#17.4) 使用 `// FIXME`: 标注问题。 ~~~ class Calculator { constructor() { // FIXME: shouldn't use a global here total = 0; } } ~~~ * [17.5](https://github.com/yuche/javascript#17.5) 使用 `// TODO`: 标注问题的解决方式。 ~~~ class Calculator { constructor() { // TODO: total should be configurable by an options param this.total = 0; } } ~~~
';