JavaScript Style Guide - jquery官网
来源:互联网 发布:怎么关闭手机数据 编辑:程序博客网 时间:2024/06/05 16:39
- Linting
- Spacing
- Bad Examples
- Good Examples
- Objects
- Arrays and Function Calls
- Multi-line Statements
- Chained Method Calls
- Full File Closures
- Assignments
- Equality
- Type Checks
- Comments
- Quotes
- Semicolons
- Naming Conventions
- Global Variables
- DOM Node Rules
- Switch Statements
- Bad Examples
- Good Examples
- Objects
- Arrays and Function Calls
- Multi-line Statements
- Chained Method Calls
- Full File Closures
Linting
Use JSHint to detect errors and potential problems. Every jQuery project has a Grunt task for linting all JavaScript files: grunt jshint
. The options for JSHint are stored in a .jshintrc
file; many repositories will have multiple .jshintrc
files based on the type of code in each directory.
Each .jshintrc
file follows a specific format. All options must be alphabetized and grouped:
{
"common1": true,
"common2": true,
"repoSpecific1": true,
"repoSpecific2": true,
"globals": {
"repoGlobal1": true,
"repoGlobal2": false
}
}
The following common options must be used in all projects:
{
"boss": true,
"curly": true,
"eqeqeq": true,
"eqnull": true,
"expr": true,
"immed": true,
"noarg": true,
"onevar": true,
"quotmark": "double",
"smarttabs": true,
"trailing": true,
"undef": true,
"unused": true
}
If the project supports browsers which do not implement ES5, then the es3
option must be included with the repo-specific options.
Spacing
In general, the jQuery style guide encourages liberal spacing for improved human readability. The minification process creates a file that is optimized for browsers to read and process.
- Indentation with tabs.
- No whitespace at the end of line or on blank lines.
- Lines should be no longer than 80 characters, and must not exceed 100 (counting tabs as 4 spaces). There are 2 exceptions, both allowing the line to exceed 100 characters:
- If the line contains a comment with a long URL.
- If the line contains a regex literal. This prevents having to use the regex constructor which requires otherwise unnecessary string escaping.
if
/else
/for
/while
/try
always have braces and always go on multiple lines.- Unary special-character operators (e.g.,
!
,++
) must not have space next to their operand. - Any
,
and;
must not have preceding space. - Any
;
used as a statement terminator must be at the end of the line. - Any
:
after a property name in an object definition must not have preceding space. - The
?
and:
in a ternary conditional must have space on both sides. - No filler spaces in empty constructs (e.g.,
{}
,[]
,fn()
) - New line at the end of each file.
- If the entire file is wrapped in a closure, the function body is not indented. See full file closures for examples.
Bad Examples
1234// Bad
if(condition) doSomething();
while(!condition) iterating++;
for(var i=0;i<100;i++) object[array[i]] = someFn(i);
// Bad
if(condition) doSomething();
while(!condition) iterating++;
for(var i=0;i<100;i++) object[array[i]] = someFn(i);
Good Examples
1234567891011121314151617181920212223var i = 0;
if ( condition ) {
doSomething();
} else if ( otherCondition ) {
somethingElse();
} else {
otherThing();
}
while ( !condition ) {
iterating++;
}
for ( ; i < 100; i++ ) {
object[ array[ i ] ] = someFn( i );
}
try {
// Expressions
} catch ( e ) {
// Expressions
}
var i = 0;
if ( condition ) {
doSomething();
} else if ( otherCondition ) {
somethingElse();
} else {
otherThing();
}
while ( !condition ) {
iterating++;
}
for ( ; i < 100; i++ ) {
object[ array[ i ] ] = someFn( i );
}
try {
// Expressions
} catch ( e ) {
// Expressions
}
Objects
Object declarations can be made on a single line if they are short (remember the line length limits). When an object declaration is too long to fit on one line, there must be one property per line. Property names only need to be quoted if they are reserved words or contain special characters:
// Bad
var map = { ready: 9,
when: 4, "you are": 15 };
// Good
var map = { ready: 9, when: 4, "you are": 15 };
// Good as well
var map = {
ready: 9,
when: 4,
"you are": 15
};
Arrays and Function Calls
Always include extra spaces around elements and arguments:
array = [ "*" ];
array = [ a, b ];
foo( arg );
foo( "string", object );
foo( options, object[ property ] );
foo( node, "property", 2 );
foo( [ a, b ], "property", { c: d } );
Exceptions:
// Function with a single line object or array as the sole argument:
// No space on either side of the argument
foo({ a: "alpha", b: "beta" });
foo([ a, b ]);
// Function with a multiline callback, object, or array as the sole argument:
// No space on either side of the argument
foo({
a: "alpha",
b: "beta"
});
// Function with a multiline callback, object, or array as the first argument:
// No space before the first argument
foo(function() {
// Do stuff
}, options );
// Function with a multiline callback, object, or array as the last argument:
// No space after after the last argument
foo( data, function() {
// Do stuff
});
Multi-line Statements
When a statement is too long to fit on one line, line breaks must occur after an operator.
// Bad
var html = "<p>The sum of " + a + " and " + b + " plus " + c
+ " is " + (a + b + c);
// Good
var html = "<p>The sum of " + a + " and " + b + " plus " + c +
" is " + (a + b + c);
Lines should be broken into logical groups if it improves readability, such as splitting each expression of a ternary operator onto its own line even if both will fit on a single line.
var baz = firstCondition( foo ) && secondCondition( bar ) ?
qux( foo, bar ) :
foo;
When a conditional is too long to fit on one line, successive lines must be indented one extra level to distinguish them from the body.
if ( firstCondition() && secondCondition() &&
thirdCondition() ) {
doStuff();
}
Chained Method Calls
When a chain of method calls is too long to fit on one line, there must be one call per line, with the first call on a separate line from the object the methods are called on. If the method changes the context, an extra level of indentation must be used.
elements
.addClass( "foo" )
.children()
.html( "hello" )
.end()
.appendTo( "body" );
Full File Closures
When an entire file is wrapped in a closure, the body of the closure is not indented.
(function( $ ) {
// this doesn't get indented
})( jQuery );
The same applies to AMD wrappers.
define([
"foo",
"bar",
"baz"
], function( foo, bar, baz ) {
// this doesn't get indented
});
For UMD, the factory is indented to visually differentiate it from the body.
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([
"jquery"
], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
// this doesn't get indented
}));
Assignments
Assignments in a declaration must be on their own line. Declarations that don't have an assignment must be listed together at the start of the declaration. Each line after the initial line must be indented once. For example:
// Bad
var foo = true;
var bar = false;
var a;
var b;
var c;
// Good
var a, b, c,
foo = true,
bar = false,
obj = {
a: b,
c: d,
},
arr = [
a,
b,
c
],
fn = function() {
body();
};
Exception: When a declaration has a single multiline assignment, the subsequent lines are not indented.
// Good
var fn = function() {
body();
};
// Bad
var fn = function() {
body();
};
Equality
Strict equality checks (===
) must be used in favor of abstract equality checks (==
). The only exception is when checking for undefined
and null
by way of null
.
// Check for both undefined and null values, for some important reason.
undefOrNull == null;
Type Checks
- String:
typeof object === "string"
- Number:
typeof object === "number"
- Boolean:
typeof object === "boolean"
- Object:
typeof object === "object"
- Plain Object:
jQuery.isPlainObject( object )
- Function:
jQuery.isFunction( object )
- Array:
jQuery.isArray( object )
- Element:
object.nodeType
- null:
object === null
- null or undefined:
object == null
- undefined:
- Global Variables:
typeof variable === "undefined"
- Local Variables:
variable === undefined
- Properties:
object.prop === undefined
typeof object === "string"
typeof object === "number"
typeof object === "boolean"
typeof object === "object"
jQuery.isPlainObject( object )
jQuery.isFunction( object )
jQuery.isArray( object )
object.nodeType
object === null
object == null
- Global Variables:
typeof variable === "undefined"
- Local Variables:
variable === undefined
- Properties:
object.prop === undefined
Comments
Comments are always preceded by a blank line. Comments start with a capital first letter, but don't require a period at the end, unless you're writing full sentences. There must be a single space between the comment token and the comment text.
Single line comments go over the line they refer to:
// We need an explicit "bar", because later in the code foo is checked.
var foo = "bar";
// Even long comments that span
// multiple lines use the single
// line comment form.
Multi-line comments are only used for file and function headers.
Inline comments are allowed as an exception when used to annotate special arguments in formal parameter lists or when needed to support a specific development tool:
function foo( types, selector, data, fn, /* INTERNAL */ one ) {
// Do stuff
}
Do not write API documentation in comments. API documentation lives in its own repository.
Quotes
jQuery uses double quotes.
var double = "I am wrapped in double quotes";
Strings that require inner quoting must use double outside and single inside.
var html = "<div id='my-id'></div>";
Semicolons
Use them. Never rely on ASI.
Naming Conventions
Variable and function names should be full words, using camel case with a lowercase first letter. Names should be descriptive but not excessively so. Exceptions are allowed for iterators, such as the use of i
to represent the index in a loop. Constructors do not need a capital first letter.
Global Variables
Each project may expose at most one global variable.
DOM Node Rules
.nodeName
must always be used in favor of .tagName
.
.nodeType
must be used to determine the classification of a node (not .nodeName
).
Switch Statements
The usage of switch
statements is generally discouraged, but can be useful when there are a large number of cases - especially when multiple cases can be handled by the same block, or fall-through logic (the default
case) can be leveraged.
When using switch
statements:
- Use a
break
for each case other thandefault
. - Align
case
statements with theswitch
.
switch ( event.keyCode ) {
case $.ui.keyCode.ENTER:
case $.ui.keyCode.SPACE:
x();
break;
case $.ui.keyCode.ESCAPE:
y();
break;
default:
z();
}
- JavaScript Style Guide - jquery官网
- Javascript style guide
- Google JavaScript Style Guide
- Airbnb JavaScript Style Guide
- Google JavaScript Style Guide
- 【翻译】Airbnb JavaScript Style Guide
- javascript格式建议(JavaScript Style Guide)
- Style Guide
- Google JavaScript Style Guide[chajn2.28 != me2.64]
- Google JavaScript Style Guide[chajn2.28 != me2.64
- FW: C++ Style Guide : C++ Style Guide
- C# Coding Style Guide
- C# Coding Style Guide
- C# Coding Style Guide
- Mozilla Coding Style Guide
- C# Coding Style Guide
- X.509 Style Guide
- Dojo Style Guide(存照)
- django 名词解释
- 动态代理
- <读书毁了我> 王强
- 【Data Structure】树状数组
- 简单的图形分割平面的通式HDU2050,5047
- JavaScript Style Guide - jquery官网
- centos安装Ambari
- struts之拦截器
- struct与enum定义及用法的总结
- 视觉直观感受 7 种常用排序算法
- (-)朴素贝叶斯学习(1)-机器学习中熵的理解
- KVC 与 KVO 理解
- 大三数据库实验报告
- GraphLab:将大数据分析从理念运用到生产