若是你的代码易于阅读,那么代码中bug也将会不多,由于一些bug能够很容被调试,而且,其余开发者参与你项目时的门槛也会比较低。所以,若是项目中有多人参与,采起一个有共识的编码风格约定很是有必要。git
以todomvc的编码要求为例:github
Example:mvc
'use strict'; function foo(bar, fum) { var i, l, ret; var hello = 'Hello'; if (!bar) { return; } for (i = 0, l = bar.length; i < l; i++) { if (bar[i] === hello) { ret += fum(bar[i]); } } return ret; }
Read idiomatic.js for general JavaScript code style best practices.app
When using anonymous functions, leave a space between the function name and opening parenthesis.dom
Example:ide
(function () { 'use strict'; var thanks = 'mate'; })
Strict mode should be used wherever possible, but must never be globally applied. Instead, use it inside an IIFE as shown aboveui
Inline comments are a great way of giving new users a better understanding of what you're doing and why.this
It's also helpful to let your functions breathe, by leaving additional lines between statements.编码
Example:spa
// Ok. var removeTodo = function (todoItem) { var todoModel = todoItem.getModel(); // Grab the model from the todoItem. todoItem.find('.destroy').click(); // Trigger a click to remove the element from the <ul>. todoModel.remove(); // Removes the todo model from localStorage. }; // Better. var removeTodo = function (todoItem) { // Grab the model from the todoItem. var todoModel = todoItem.getModel(); // Trigger a click to remove the element from the <ul>. todoItem.find('.destroy').click(); // Removes the todo model from localStorage. todoModel.remove(); };
When using RequireJS, please format your code to these specifications:
define('Block', [ 'jQuery', 'Handlebars' ], function ($, Handlebars) { 'use strict'; // Code here. });
When you submit your pull request, one of the first things we will do is run JSHint against your code.
You can help speed the process by running it yourself:
jshint path/to/your/app/js
Your JSHint code blocks must follow this style:
/*global define, App */ /*jshint unused:false */
http://www.iteye.com/news/28028-JavaScript-code-style-guide