In daily work, if we want to write high quality code, write beautiful, it must need a set of code specifications, the following code specifications are from Jingdong Cave laboratory, here also want to keep notes for daily review.
CSS code specification
Code style.
There are two styles of style writing, Compact
.jdc{ dispaly: block; width: 50px; }Copy the code
One is called Expanded
.jdc {
dispaly: block;
width: 50px;
}
Copy the code
Uniform convention expansion format writing in the team
Code case
The style selector, attribute name, and attribute value keywords are all written in lower case, and the attribute string is case-sensitive.
Recommend * / / *
.jdc {
display: block;
}
Copy the code
/* not recommended */
.JDC {
DISPLAY: BLOCK;
}
Copy the code
The selector
* Do not use ID selectors. Do not use tag selectors without specific semantic definitions
Recommend * / / *
.jdc {}
.jdc li {}
.jdc li p {}
Copy the code
/* not recommended */* {}#jdc {}
.jdc div{}
Copy the code
Code indentation
Use four Spaces to indent code so that all editors behave the same (each editor has its own configuration)
.jdc {
width: 100%;
height: 100%;
}
Copy the code
A semicolon
Each attribute declaration ends with a semicolon;
.jdc {
width: 100%;
height: 100%;
}
Copy the code
Code legibility
A space between the open parenthesis and the class name, and a space between the colon and the attribute
Recommendation:
.jdc {
width: 100%;
}
Copy the code
Is not recommended:
.jdc{
width:100%;
}
Copy the code
Comma-separated values, followed by a space
Recommendation:
.jdc {
box-shadow: 1px 1px 1px # 333.2px 2px 2px #ccc;
}
Copy the code
Is not recommended:
.jdc {
box-shadow: 1px 1px 1px # 333.2px 2px 2px #ccc;
}
Copy the code
Opens a new line for a single CSS selector or new declaration
Recommendation:
.jdc..jdc_logo..jdc_hd {
color: #ff0;
}
.nav {
color: #fff;
}
Copy the code
Is not recommended:
.jdc..jdc..jdc_hd{
color: #ff0;
}.nav{
color: #fff;
}
Copy the code
Color Value RGB () RGBA () HSL () HSLA () Rect () does not contain Spaces, and the value does not contain an unnecessary 0
Recommendation:
.jdc {
color: rgba(255.255.255.5);
}
Copy the code
Is not recommended:
.jdc {
color: rgba( 255.255.255.5);
}
Copy the code
Property value Hexadecimal value can be abbreviated if possible
Recommendation:
.jdc {
color: #fff;
}
Copy the code
Is not recommended:
.jdc {
color: #ffffff;
}
Copy the code
Do not specify unit recommendations for 0:
.jdc {
margin: 0 10px;
}
Copy the code
Is not recommended:
.jdc {
margin: 0px 10px;
}
Copy the code
attribute
Attribute value quotes
Single quotation marks are used for CSS attribute values
Recommend * / / *
.jdc {
font-family: 'Hiragino Sans GB';
}
Copy the code
/* not recommended */
.jdc {
font-family: "Hiragino Sans GB";
}
Copy the code
Attribute writing order
The following order is recommended:
Display/position/float/clear/visibility/overflow display/position/float/clear/visibility/overflow Width/height/margin/padding/border/background Color/font/text-decoration/text-align/vertical-align/white-space/break-word content / cursor / border-radius / box-shadow /text-shadow / background:linear-gradient
.jdc {
display: block;
position: relative;
float: left;
width: 100px;
height: 100px;
margin: 0 10px;
padding: 20px 0;
font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif;
color: # 333;
background: rgba(0.0.0.5);
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
-o-border-radius: 10px;
-ms-border-radius: 10px;
border-radius: 10px;
}
Copy the code
CSS3 private prefix
The CSS3 browser private prefix precedes the standard prefix
.jdc {
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
-o-border-radius: 10px;
-ms-border-radius: 10px;
border-radius: 10px;
}
Copy the code
JS code specification
Language specification
JavaScript is a client-side scripting language, and here are the rules you need to follow when writing JavaScript.
reference
Const and let are both block-level scopes, and var is function-level scopes
Const and let only exist in the blocks they define
{
let a = 1
const b = 1
}
console.log(a) // ReferenceError
console.log(b) // ReferenceError
Copy the code
- Use const for all references and do not use var
Reason: This ensures that you can’t reassign references to avoid errors and unintelligible code
// bad
var a = 1
var b = 2
// good
const a = 1
const b = 2
Copy the code
- If the reference is mutable, use let instead of var
Reason: Let is block-scoped, unlike VAR, which is function-scoped
// bad
var count = 1
if (count < 10) {
conut += 1
}
// good
let count = 1
if (count < 10) (
count += 1
)
Copy the code
object
- Create objects using literal values
// bad
const a = new Object{}
// good
const a = {}
Copy the code
- Do not use reserved words as keys for objects, as this will not run under IE8
// bad
const a = {
default: {}, // Default is reserved
common: {}}// good
const a = {
defaults: {},
common: {}}Copy the code
- When you create an object with a dynamic property name, use the object calculation property name to create the object
Reason: Because doing so allows you to define all object properties in one place
function getKey(k) {
return `a key named ${k}`
}
// bad
const obj = {
id: 5.name: 'San Francisco'
};
objp[getKey('enabled')] = true
// good
const obj = {
id: 5.name: 'San Francisco',
[getKey('enabled')]: true
}
Copy the code
- Use the shorthand for object methods
// bad
const item = {
value: 1.addValue: function (val) {
return item.value + val
}
}
// good
const item = {
value: 1,
addValue (val) {
return item.value + val
}
}
Copy the code
- Use the shorthand for the value of an object property
Reason: It’s shorter and clearer
const job = 'FrontEnd'
// bad
const item = {
job: job
}
// good
const item = {
job
}
Copy the code
- Group abbreviated object attributes at the beginning of the object declaration
Reason: This makes it easier to tell which attributes are abbreviated
const job = 'FrontEnd'
const department = 'JDC'
// bad
const item = {
sex: 'male',
job,
age: 25,
department
}
// good
const item = {
job,
department,
sex: 'male'.age: 25
}
Copy the code
- Use quotation marks only for attributes with invalid identifiers
Reason: Because in general we think it’s subjectively easier to read, which leads to improved code highlighting and optimizations by major JS engines
// bad
const bad = {
'foo': 3.'bar': 4.'data-blah': 5
}
// good
const good = {
foo: 3.bar: 4.'data-blah': 5
}
Copy the code
- Don’t directly use object. prototype methods such as hasOwnProperty, propertyIsEnumberable and isPrototypeOf
Cause: These methods may be overridden by the Object’s own property of the same name – such as {hasOwnProperty: false} or the Object may be a null Object (object.create (null)).
// bad
console.log(object.hasOwnProperty(key))
// good
console.log(object.prototype.hasOwnProperty.call(object, key))
// best
const has = Object.prototype.hasOwnProperty // cache the lookup once, in module scope.
console.log(has.call(object, key)
)
/* or */
import has from 'has' // https://www.npmjs.com/package/has
console.log(has(object, key))
Copy the code
- Preference for object expansion operators… To make a shallow copy of the Object instead of using Object.assgin, use the Object residual operator to get a new Object containing the identified residual attributes
// very bad
const original = { a: 1.b: 2 }
const copy = Object.assgin(original, { c: 3 }) // Changes the original array
// bad
const original = { a: 1.b: 2 }
const copy = Object.assgin({}, original, { c: 3 }) // copy => { a: 1, b: 2, c: 3}
// good
const original = { a: 1.b: 2 }
constcopy = { ... original,c: 3} // copy => { a: 1, b: 2, c: 3 }
const{ a, ... noA } = copy// noA => { b: 2, c: 3 }
Copy the code
An array of
- Create an array using literal values
// bad
const items = new Array(a)// good
const item = []
Copy the code
- When adding elements to an array, use the push method
const items = []
// bad
items[items.length] = 'test'
// good
items.push('test')
Copy the code
- Using the expansion operator… Copy the array
// bad
const items = []
const itemsCopy = []
const len = items.length
let i
// bad
for (i = 0; i < len; i++) {
itemsCopy[i] = items[i]
}
// good
itemsCopy = [...items]
Copy the code
- To convert an iterable object into an array, use the expansion operator… Instead of an Array. The from
const foo = document.querySelectorAll('.foo')
// good
const nodes = Array.from(foo)
// best
const nodes = [...foo]
Copy the code
- Convert an array-like object to an Array using array. from
const arrLike = { 0: 'foo'.1: 'bar'.2: 'baz'.length: 3}
// bad
const arr = Array.prototype.slice.call(arrLike)
// good
const arr = Array.from(arrLike)
Copy the code
- Use array. from instead of the extension operator when iterating over the mapping… Because it avoids creating intermediate arrays
// bad
const baz = [...foo].map(bar)
// good
const baz = Array.from(foo, bar)
Copy the code
- When using a method such as an array map, use a return declaration. In the case of a single declaration statement, omit the return declaration
// good
[1.2.3].map(x= > {
const y = x + 1
return x * y
})
// good
[1.2.3].map(x= > x + 1)
// bad
const flat = {}
[[0.1], [2.3], [4.5]].reduce((memo, item, index) = > {
const flatren = memo.concat(item)
flat[index] = flatren
})
// good
const flat = {}
[[0.1], [2.3], [4.5]].reduce((memo, item, index) = > {
const flatren = memo.concat(item)
flat[index] = flatren
return flatten
})
// bad
inbox.filter((msg) = > {
const { subject, author } = msg
if (subject === 'Mockingbird') {
return author === 'Harper Lee'
} else {
return false}})// good
inbox.filter((msg) = > {
const { subject, author } = msg
if (subject === 'Mockingbird') {
return author === 'Harper Lee'
}
return false
})
Copy the code
- If an array has more than one line, use the new line after the opening parentheses and before the closing parentheses
// bad
const arr = [
[0.1], [2.3], [4.5]]const objectInArray = [{
id: 1
}, {
id: 2
}]
const numberInArray = [
1.2
]
// good
const arr = [[0.1], [2.3], [4.5]]
const objectInArray = [
{
id: 1
},
{
id: 2}]const numberInArray = [
1.2
]
Copy the code
Structure assignment
- Use structural assignment when you need to use multiple attributes of an object
Level 2 nesting wishes: Structures avoid creating temporary references to attributes
// bad
function getFullName (user) {
const firstName = user.firstName
const lastName = user.lastName
return `${firstName} ${lastName}`
}
// good
function getFullName (user) {
const { firstName, lastName } = user
return `${firstName} ${lastName}`
}
// better
function getFullName ({ firstName, lastName }) {
return `${firstName} ${lastName}`
}
Copy the code
- When you need to use multiple values of an array, use structural assignment as well
const arr = [1.2.3.4]
// bad
const first = arr[0]
const second = arr[1]
// good
const [first, second] = arr
Copy the code
-
When a function needs to return multiple values, use the structure of an object, not an array
Reason: Attribute order can be added or changed at any time, nondestructively
// bad
function doSomething () {
return [top, right, bottom, left]
}
// If it is an array structure, then the order of the data needs to be considered when calling
const [top, xx, xxx, left] = doSomething
// good
function doSomething () {
return {top, right, bottom, left}
}
// There is no need to consider the order of the data
const { top, left } = doSomething
Copy the code
string
- Use single quotation marks for strings.
// bad
const department = "JDC"
// good
const department = 'jdc'
Copy the code
- When the string is too long, do not use the string concatenator \, but use + instead
const str = 'Bump Lab bump Lab Bump Lab bump Lab' +
'Bump Lab bump Lab Bump Lab bump Lab' +
'Bump Lab bump Lab'
Copy the code
- When programmatically generating strings, use template strings
const test = 'test'
// bad
cosnt str = ['a'.'b', test].join()
// bad
const str = 'a' + 'b' + test
// good
const str = `ab${test}`
Copy the code
- Do not use eval() on strings; it leads to too many bugs
- Do not use unnecessary escape characters in strings
// bad
const foo = '\'this\' \i\s \"quoted\"'
// good
const foo = '\'this\' is "quoted"'
const foo = `my name is '${name}'`
Copy the code
function
- Do not use the Function constructor to create functions
Reason: Creating functions this way creates vulnerabilities just like using eval() on strings
// bad
const add = new Function('a'.'b'.'return a + b')
// still bad
const subtract = Function('a'.'b'.'return a + b')
Copy the code
- Use Spaces in function signatures
// bad
const f = function(){}
const g = function (){}
const c = function() {}
// good
const x = function b () {}
const y = function c () {}
Copy the code
- Use named function expressions instead of function declarations
The reason for doing so is that function declarations are elevated, which means that it is easy to refer to the function before it is defined in the file, which is bad for readability and maintainability. If you find that the function definition is too large and complex to understand the rest of the file, maybe you should break it up into modules! Don’t forget to name the expression explicitly, regardless of whether the name is inferred from the included variable (often found in modern browsers or when using the Babel compiler). This eliminates any assumptions in the error call stack. (the discussion)
// bad
function foo () {
// ...
}
// bad
const foo = function () {
// ...
}
// good
// lexical name distinguished from the variable-referenced invocation(s)
const short = function longUniqueMoreDescriptiveLexicalFoo () {
// ...
}
Copy the code
- Wrap self-executing anonymous functions in parentheses
Why: An immediately executed anonymous function expression is a single unit, and wrapping it and its call parentheses in parentheses makes this clear. Note that IIFE is hardly needed in a world full of modules.
// immediately-invoked function expression (IIFE)
(function () {
console.log('Welcome to the Internet. Please follow me.')
}())
Copy the code
- Do not declare functions in non-functional blocks of code (if, while, etc.)
// bad
if (isUse) {
function test () {
// do something}}// good
let test
if (isUse) {
test = () = > {
// do something}}Copy the code
- Do not name arguments as arguments will take precedence over arguments objects that previously existed in each function scope
// bad
function foo (name, options, arguments) {
// ...
}
// good
function foo (name, options, args) {
// ...
}
Copy the code
- Instead of arguments, use residual operators…
Arguments is just an array of classes, and… It’s a real array
// bad
function test () {
const args = Array.prototype.slice.call(arguments)
return args.join(' ')}// good
function test (. args) {
return args.join(' ')}Copy the code