Code writing specification - Javascript

Wen Yuan 2022-06-24 07:32:19 阅读数:120

codewritingspecificationjavascript

JavaScript standard

This code specification applies to my personal project , At the time of formulation , The code documents of some large manufacturers and open source organizations are used for reference .

Curly braces

In most of JavaScript In the project , Curly brackets with 「Egyptian」 Style writing , That is, the left curly bracket is on the same line as the corresponding keyword , Not a new line . There should be a space before the left bracket , As shown below :

recommend :

if (foo) {
bar()
} else {
baz()
}

Not recommended :

if (foo)
{
bar()
}
else
{
baz()
}

Single line code block

Use spaces in single line blocks .

recommend :

function foo () { return true }
if (foo) { bar = 0 }

Not recommended :

function foo () {return true}
if (foo) {bar = 0}

Indent

There are three common indents :2 A space 、4 A space 、Tab tabs .

This specification refers to outstanding open source projects in the market , Let's agree to use Space To indent , And the indentation uses two spaces .

The key value of the object literal is indented

There cannot be a space between the key and the value of an object literal , There is a space between the colon and the value of the object literal .

recommend :

const obj = { 'foo': 'haha' }

Not recommended :

const obj = { 'foo' : 'haha' }

Constructor initial is uppercase

stay JavaScript in new Operator is used to create an instance of a particular type of object , An object of this type is represented by a constructor .

Because the constructor is just a regular function , The only difference is the use of new To call . So we agreed that the first letter of the constructor should be capitalized , To distinguish between constructors and ordinary functions .

recommend :

const fooItem = new Foo()

Not recommended :

const fooItem = new foo()

Trailing newline

In a non empty file , The existence of trailing newlines is a common UNIX style , Its advantage is that it is convenient to concatenate and append files without interruption Shell A hint of . In daily projects , The advantage of keeping trailing newlines is , It can reduce code conflicts during version control .

recommend :

function func () {
// do something
}
// Here is a new line 

Not recommended :

function func () {
// do something
}

Blank line

Blank lines are helpful for separating code logic , But too many blank lines will take up space on the screen , Affect readability . The agreed maximum number of continuous blank lines is 2.

recommend :

const a = 1
const b = 2

Not recommended :

const a = 1
const b = 2

Variable declarations

JavaScript Allow in a declaration , Declare multiple variables . But we agreed that when declaring variables , A declaration can only have one variable .

recommend :

const a
const b
const c

Not recommended :

const a, b, c

A semicolon

Every statement should be followed by a semicolon , Even if it can be skipped .

JavaScript In all classes C Language is quite unique , It does not need a semicolon at the end of each statement . In many cases ,JavaScript The engine can determine where a semicolon should be and automatically add it . This feature is called automatic semicolon insertion (ASI), Is considered to be JavaScript The more controversial features of .

Whether semicolons should be used in the industry , There are also many arguments , This specification Semicolons are recommended , This can avoid possible pitfalls .

There are two cases where you can avoid using a semicolon :

  • If you are an experienced JavaScript The programmer , You can choose to look like StandardJS Such a semicolon free code style .
  • In the use of Vue.js When preparing projects for such modernization frameworks , Follow the code style of the framework itself ( Without a semicolon ).

Code block spaces

Consistency is an important part of any style guide . Although where to place open brackets for blocks is purely personal preference , But it should be consistent throughout the project . Inconsistent styles will distract the reader from reading the code .

We agreed to add a space before the code block .

recommend :

if (a) {
b()
}
function a() {}

Not recommended :

if (a){
b()
}
function a(){}

Function declaration space

This specification stipulates that there is no space before the function bracket .

recommend :

function func(x) {
// ...
}

Not recommended :

function func (x) {
// ...
}

Operator space

You need to add spaces before and after the operator .

recommend :

const sum = 1 + 2

Not recommended :

const sum = 1+2

Function position

If you are writing a few 「 auxiliary 」 Functions and some code that uses them , We have an agreement Write the calling code first , Write the function again .

This is because when reading the code , The first thing we want to know is 「 What it did 」. If the code goes first , So this information is shown at the beginning of the whole program . after , Maybe we don't need to read these functions , Especially when their names clearly show their functions .

recommend :

// The code that calls the function
let elem = createElement();
setHandler(elem);
walkAround();
// --- Auxiliary function ---
function createElement() {
...
}
function setHandler(elem) {
...
}
function walkAround() {
...
}

Annotation specifications

Single-line comments

One row must be exclusive .// Followed by a space , Indent is consistent with the code annotated on the next line .

Multiline comment

Avoid using /*...*/ Such multiline comments . When there are multiple lines of comment content , Use multiple single line comments .

function / Method notes

  • Must include a description of the function , explain what, instead of how.
  • When there are parameters and return values , There must be a comment mark .
  • Parameters and return values must contain type information and descriptions .
  • When a function is an internal function , When external access is not available , have access to @inner To mark .

recommend :

/**
* Number formatting
* like 10000 => 10k
* @param {number} num
* @param {number} digits
* @return {string}
*/
function numberFormatter(num, digits) {
const si = [
{ value: 1E18, symbol: 'E' },
{ value: 1E15, symbol: 'P' },
{ value: 1E12, symbol: 'T' },
{ value: 1E9, symbol: 'G' },
{ value: 1E6, symbol: 'M' },
{ value: 1E3, symbol: 'k' }
]
for (let i = 0; i < si.length; i++) {
if (num >= si[i].value) {
return (num / si[i].value).toFixed(digits).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + si[i].symbol
}
}
return num.toString()
}

File Comments

  • Used to tell readers unfamiliar with this code what this file contains .
  • Document notes should indicate the author 、 Document version 、 establish / Modification time 、 Major revision records .

recommend :

/**
* @desc Description of file, its uses and information
* @dependencies about its dependencies.
* @author Author Name
* @date 2020-12-29
*/

Articles are constantly updated , this paper GitHub Front end cultivation Booklet Included , welcome Star. If you have different opinions on the content of the article , Welcome to leave a message .

copyright:author[Wen Yuan],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/175/20210630195005988T.html