1 introduction

As the number of people on the team grows, everyone has different coding preferences and code styles. If there is a common code specification that everyone is willing to abide by, it will be more efficient and avoid code Review and refactoring.

Part of the rules refer to the code specification of Tencent Alloyteam, if there are any mistakes, please point out, we will be very grateful.

Adhere to good code style norms, starting with you and me.

2 Naming Conventions

1) Project naming

Use all lowercase letters and delimit by underscore.

Example: my_project_name

2) Directory naming

Refer to project naming rules;

When there is a complex number structure, use the plural nomenclature.

Examples: Pages, assets, directives, Components, mixins, utils

3)javaScriptThe file name

Refer to the project naming rules.

Example: account_model. Js

4)CSS.lessThe file name

Refer to the project naming rules.

Example: retina_sprites. Less

5) NAME the HTML file

Refer to the project naming rules.

Example: error_report. HTML

6) If usedVueorReactTechnology stack, componentsComponentnamed

All component names need to be capitalized and then humped

Example: CalendarList. Vue

3 HTML

1) grammar

  • Indent using soft TAB (4 Spaces);
  • Nested nodes should be indented;
  • On attributes, use double quotes, not single quotes;
  • Attribute names are all lowercase, delimited by hyphens.
  • Don’t use slashes at the end of auto-closing tags (the HTML5 specification states that they are optional);
  • Do not ignore optional closing tags;

      
<html>
    <head>
        <title>Page title</title>
    </head>
    <body>
        <img src="images/company_logo.png" alt="Company" />

        <h1 class="hello-world">Hello, world!</h1>
    </body>
</html>
Copy the code

2) HTML5 doctype

Use this simple docType at the beginning of the page to enable standard mode, rendering it as consistently as possible across browsers;

Although docType is case insensitive, by convention, docType is uppercase (uppercase or lowercase for HTML attributes).


      
<html>.</html>
Copy the code

3) the lang attribute

According to the HTML5 specification:

The LANG attribute should be attached to the HTML tag. This will help voice tools and translation tools tell them how to pronounce and translate.

More on lang properties are explained here;

You can find a list of languages on SitePoint;

However, Sitepoint only gives the language categories, for example, Chinese only gives zh, but does not distinguish Between Hong Kong, Taiwan and mainland. Microsoft has a more detailed list, which breaks down zh-CN, zh-HK, and zh-TW.


      
<html lang="en-us">.</html>
Copy the code

4) Character encoding

Allows browsers to quickly and easily determine the appropriate rendering method for web content by declaring an explicit character encoding, usually specified as ‘UTF-8’.


      
<html>
    <head>
        <meta charset="UTF-8">
    </head>.</html>
Copy the code

5) IE compatible mode

The ‘ ‘tag allows you to specify which version of IE the page should be rendered with;

If you want to learn more, click here;

Different doctypes trigger different rendering modes in different browsers (this article summarizes them nicely).


      
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    </head>.</html>
Copy the code

6) Introduce CSS, JS

According to the HTML5 specification, there is usually no need to specify type when importing CSS and JS, since text/ CSS and text/javascript are their default values, respectively.

HTML5 specification link

  • Use the link
  • Use the style
  • Use the script
<! -- External CSS -->
<link rel="stylesheet" href="code_guide.css">

<! -- In-document CSS -->
<style>.</style>

<! -- External JS -->
<script src="code_guide.js"></script>

<! -- In-document JS -->
<script>.</script>
Copy the code

7) Order of attributes

Attributes should appear in a specific order to ensure readability;

  • class
  • id
  • name
  • data-*
  • src.for.type.href.value , max-length.max.min.pattern
  • placeholder.title.alt
  • aria-*.role
  • required.readonly.disabled

Class is designed for highly reusable components and should come first;

Id is specific and should be used sparingly, so put it in second place.

<a class="..." id="..." data-modal="toggle" href="#">Example link</a>

<input class="form-control" type="text">

<img src="..." alt="...">
Copy the code

8) Boolean attributes

Boolean attributes are attributes that do not require a value to be declared. XHTML requires a value for each attribute, but HTML5 does not.

WhatWG Section on Boolean Attributes for more information:

The Boolean property is true if it exists, false if it does not.

<input type="text" disabled>

<input type="checkbox" value="1" checked>

<select>
    <option value="1" selected>1</option>
</select>
Copy the code

9) JS generates labels

Generating tags in JS files makes content harder to find, harder to edit, and worse performance. This should be avoided as much as possible.

10) Reduce the number of labels

When writing HTML code, you need to avoid redundant parent nodes;

Many times, you need to iterate and refactor to make HTML less.

<! -- Not recommended -->
<span class="avatar">
    <img src="...">
</span>

<! -- Suggest doing so -->
<img class="avatar" src="...">
Copy the code

11) Practical over perfect

Try to follow HTML standards and semantics, but not at the expense of usability;

Solve problems with as little complexity and as few tags as possible at all times.

4 CSS, less

1) the indentation

Use soft TAB (4 Spaces)

.element {
    position: absolute;
    top: 10px;
    left: 10px;

    border-radius: 10px;
    width: 50px;
    height: 50px;
}
Copy the code

2) a semicolon

Each property declaration ends with a semicolon.

.element {
    width: 20px;
    height: 20px;

    background-color: red;
}
Copy the code

3) the blank space

Spaces are not required in the following cases:

  • The property name after
  • Multiple rule delimiters before ‘,’
  • ! important‘! After the ‘
  • Property value before ‘(‘ after and ‘)’
  • Don’t have extra space at the end of the line

Spaces are required in the following cases:

  • Attribute values before
  • Selectors ‘>’, ‘+’, ‘~’ before and after
  • ‘{‘ before
  • ! important‘! Before ‘
  • @elseBefore and after
  • Property value after ‘,’
  • Comments’ /‘and’Before/’
/* not good */
.element {
    color :red! important;
    background-color: rgba(0.0.0.5);
}

/* good */
.element {
    color: red ! important;
    background-color: rgba(0.0.0.5);
}

/* not good */
.element ,
.dialog{... }/* good */
.element..dialog{}/* not good */
.element>.dialog{... }/* good */
.element > .dialog{... }/* not good */
.element{... }/* good */
.element{... }/* not good */
@debug: true;

header {
  background-color: (yellow)when(@debug = true);
}


/* good */
header {
  background-color: (yellow) when (@debug = true);
}
Copy the code

4) a blank line

Blank lines are required in the following cases:

  • Leave a blank line at the end of the file
  • ‘}’ should be followed by a blank line, including nested rules in SCSS
  • Appropriate blank lines are required between attributes, as described in attribute declaration order
/* not good */
.element{... }.dialog {
    color: red;
    &:after{... }}/* good */
.element{... }.dialog {
    color: red;

    &:after{... }}Copy the code

5) comments

Use ‘/* */’ for comments (SCSS also do not use ‘//’), refer to the right side of the notation;

Indent the same as the next line of code;

Can be at the end of a line of code, separated by a space from the code.

/* Modal header */
.modal-header{... }/* * Modal header */
.modal-header{... }.modal-header {
    /* 50px */
    width: 50px;

    color: red; /* color red */
}
Copy the code

6) quotes

Use double quotation marks on the outermost layer;

The content of the URL should be quoted;

Attribute values in attribute selectors need quotes.

.element:after {
    content: "";
    background-image: url("logo.png");
}

li[data-type="single"]{... }Copy the code

7)named

  • Use the name of the classLowercase lettersIn order toIn the lineseparated
  • Id usedcamelnamed
  • lessIn the variable, function toIn the lineSeparation of naming
/* class */
.element-content{... }/* id */
#myDialog{... }/ * * / variable
@color-black: # 000;

/* mixins */
.my-mixin() {
  color: black;
}

Copy the code

8)Order of property declaration

Related attribute declarations are grouped in the order on the right, with a blank line between the groups.

.declaration-order {
    display: block;
    float: right;

    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 100;

    border: 1px solid #e5e5e5;
    border-radius: 3px;
    width: 100px;
    height: 100px;

    font: normal 13px "Helvetica Neue", sans-serif;
    line-height: 1.5;
    text-align: center;

    color: # 333;
    background-color: #f5f5f5;

    opacity: 1;
}
Copy the code

The writing sequence is:

Position display float left top right bottom Overflow Clear Z-index

(2) Own attributes: width height padding border margin background

(3) text style: font-family font-family font-family font-family: ‘Times New Roman’, ‘times New Roman’, ‘times New Roman’, ‘times New Roman’

(4) Text attribute text-align vertical-align text-wrap text-transform text-indent text-decoration letter-spacing word-spacing white-space text-overflow

Objective: To reduce browser reflow and improve browser dom rendering performance

How it works: The browser's rendering flow is as follows:

1, parsing HTML to build a DOM tree, parsing CSS to build a CSS tree: parsing HTML into a tree data structure, parsing CSS into a tree data structure

2, build the render tree: DOM tree and CSS tree after the combination of the render tree.

3. Layout the Render tree: With the Render tree, the browser already knows what nodes are in those pages, the CSS definitions of each node and their dependencies, to figure out where each node is on the screen.

4, render tree: according to the calculated rules, through the graphics card to draw the content on the screen.

CSS style parsing to display on the browser screen occurs in step 234, it can be seen that the browser does not immediately start parsing CSS style, but according to the CSS style writing order according to the DOM tree structure of render style distribution, complete step 2, and then start parsing CSS style through each tree node. The CSS styles are traversed in exactly the same order as they were written before. During parsing, if the browser finds that a change in the positioning of an element affects the DOM, it needs to be rerendered.

Correct order of writing:

.demo{
    width: 100px;
	height: 100px;
	background-color: red ;
    
	position: absolute;
}
Copy the code

Suddenly found that when the browser parses to position the element is absolutely positioned elements need from the document flow, and is carried out in accordance with the common element analytic before, so have to render, cancel the position of the element in the document, however, because of the element placeholder changes, other elements may also be affected by it return to position. As a result, step (3) takes too long, which affects the display of step (4) and affects user experience.

// Here is the order of recommended attributes
[ [ "display", "visibility", "float", "clear", "overflow", "overflow-x", "overflow-y", "clip", "zoom" ].[ "table-layout", "empty-cells", "caption-side", "border-spacing", "border-collapse", "list-style", "list-style-position", "list-style-type", "list-style-image" ].[ "-webkit-box-orient", "-webkit-box-direction", "-webkit-box-decoration-break", "-webkit-box-pack", "-webkit-box-align", "-webkit-box-flex" ].[ "position", "top", "right", "bottom", "left", "z-index" ].[
        "margin",
        "margin-top",
        "margin-right",
        "margin-bottom",
        "margin-left",
        "-webkit-box-sizing",
        "-moz-box-sizing",
        "box-sizing",
        "border",
        "border-width",
        "border-style",
        "border-color",
        "border-top",
        "border-top-width",
        "border-top-style",
        "border-top-color",
        "border-right",
        "border-right-width",
        "border-right-style",
        "border-right-color",
        "border-bottom",
        "border-bottom-width",
        "border-bottom-style",
        "border-bottom-color",
        "border-left",
        "border-left-width",
        "border-left-style",
        "border-left-color",
        "-webkit-border-radius",
        "-moz-border-radius",
        "border-radius",
        "-webkit-border-top-left-radius",
        "-moz-border-radius-topleft",
        "border-top-left-radius",
        "-webkit-border-top-right-radius",
        "-moz-border-radius-topright",
        "border-top-right-radius",
        "-webkit-border-bottom-right-radius",
        "-moz-border-radius-bottomright",
        "border-bottom-right-radius",
        "-webkit-border-bottom-left-radius",
        "-moz-border-radius-bottomleft",
        "border-bottom-left-radius",
        "-webkit-border-image",
        "-moz-border-image",
        "-o-border-image",
        "border-image",
        "-webkit-border-image-source",
        "-moz-border-image-source",
        "-o-border-image-source",
        "border-image-source",
        "-webkit-border-image-slice",
        "-moz-border-image-slice",
        "-o-border-image-slice",
        "border-image-slice",
        "-webkit-border-image-width",
        "-moz-border-image-width",
        "-o-border-image-width",
        "border-image-width",
        "-webkit-border-image-outset",
        "-moz-border-image-outset",
        "-o-border-image-outset",
        "border-image-outset",
        "-webkit-border-image-repeat",
        "-moz-border-image-repeat",
        "-o-border-image-repeat",
        "border-image-repeat",
        "padding",
        "padding-top",
        "padding-right",
        "padding-bottom",
        "padding-left",
        "width",
        "min-width",
        "max-width",
        "height",
        "min-height",
        "max-height"
    ].[ "font", "font-family", "font-size", "font-weight", "font-style", "font-variant", "font-size-adjust", "font-stretch", "font-effect", "font-emphasize", "font-emphasize-position", "font-emphasize-style", "font-smooth", "line-height", "text-align", "-webkit-text-align-last", "-moz-text-align-last", "-ms-text-align-last", "text-align-last", "vertical-align", "white-space", "text-decoration", "text-emphasis", "text-emphasis-color", "text-emphasis-style", "text-emphasis-position", "text-indent", "-ms-text-justify", "text-justify", "letter-spacing", "word-spacing", "-ms-writing-mode", "text-outline", "text-transform", "text-wrap", "-ms-text-overflow", "text-overflow", "text-overflow-ellipsis", "text-overflow-mode", "-ms-word-wrap", "word-wrap", "-ms-word-break", "word-break" ].[ "color", "background", "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader", "background-color", "background-image", "background-repeat", "background-attachment", "background-position", "-ms-background-position-x", "background-position-x", "-ms-background-position-y", "background-position-y", "-webkit-background-clip", "-moz-background-clip", "background-clip", "background-origin", "-webkit-background-size", "-moz-background-size", "-o-background-size", "background-size" ].[ "outline", "outline-width", "outline-style", "outline-color", "outline-offset", "opacity", "filter:progid:DXImageTransform.Microsoft.Alpha(Opacity", "-ms-filter:\\'progid:DXImageTransform.Microsoft.Alpha", "-ms-interpolation-mode", "-webkit-box-shadow", "-moz-box-shadow", "box-shadow", "filter:progid:DXImageTransform.Microsoft.gradient", "-ms-filter:\\'progid:DXImageTransform.Microsoft.gradient", "text-shadow" ].[
        "-webkit-transition",
        "-moz-transition",
        "-ms-transition",
        "-o-transition",
        "transition",
        "-webkit-transition-delay",
        "-moz-transition-delay",
        "-ms-transition-delay",
        "-o-transition-delay",
        "transition-delay",
        "-webkit-transition-timing-function",
        "-moz-transition-timing-function",
        "-ms-transition-timing-function",
        "-o-transition-timing-function",
        "transition-timing-function",
        "-webkit-transition-duration",
        "-moz-transition-duration",
        "-ms-transition-duration",
        "-o-transition-duration",
        "transition-duration",
        "-webkit-transition-property",
        "-moz-transition-property",
        "-ms-transition-property",
        "-o-transition-property",
        "transition-property",
        "-webkit-transform",
        "-moz-transform",
        "-ms-transform",
        "-o-transform",
        "transform",
        "-webkit-transform-origin",
        "-moz-transform-origin",
        "-ms-transform-origin",
        "-o-transform-origin",
        "transform-origin",
        "-webkit-animation",
        "-moz-animation",
        "-ms-animation",
        "-o-animation",
        "animation",
        "-webkit-animation-name",
        "-moz-animation-name",
        "-ms-animation-name",
        "-o-animation-name",
        "animation-name",
        "-webkit-animation-duration",
        "-moz-animation-duration",
        "-ms-animation-duration",
        "-o-animation-duration",
        "animation-duration",
        "-webkit-animation-play-state",
        "-moz-animation-play-state",
        "-ms-animation-play-state",
        "-o-animation-play-state",
        "animation-play-state",
        "-webkit-animation-timing-function",
        "-moz-animation-timing-function",
        "-ms-animation-timing-function",
        "-o-animation-timing-function",
        "animation-timing-function",
        "-webkit-animation-delay",
        "-moz-animation-delay",
        "-ms-animation-delay",
        "-o-animation-delay",
        "animation-delay",
        "-webkit-animation-iteration-count",
        "-moz-animation-iteration-count",
        "-ms-animation-iteration-count",
        "-o-animation-iteration-count",
        "animation-iteration-count",
        "-webkit-animation-direction",
        "-moz-animation-direction",
        "-ms-animation-direction",
        "-o-animation-direction",
        "animation-direction"
    ].[ "content", "quotes", "counter-reset", "counter-increment", "resize", "cursor", "-webkit-user-select", "-moz-user-select", "-ms-user-select", "user-select", "nav-index", "nav-up", "nav-right", "nav-down", "nav-left", "-moz-tab-size", "-o-tab-size", "tab-size", "-webkit-hyphens", "-moz-hyphens", "hyphens", "pointer-events" ]
]
Copy the code

9) color

Color hexadecimal lowercase letters;

Use abbreviations for hexadecimal colors.

/* not good */
.element {
    color: #ABCDEF;
    background-color: # 001122;
}

/* good */
.element {
    color: #abcdef;
    background-color: # 012;
}
Copy the code

10) Property shorthand

Property abbreviations require you to be very clear about the correct order of property values, and in most cases you do not need to set all the values contained in property abbreviations, so separate declarations are recommended to be clearer;

Margin, as opposed to padding, needs to be abbreviated;

Common property abbreviations include:

  • font
  • background
  • transition
  • animation
/* not good */
.element {
    transition: opacity 1s linear 2s;
}

/* good */
.element {
    transition-delay: 2s;
    transition-timing-function: linear;
    transition-duration: 1s;
    transition-property: opacity;
}
Copy the code

11)Media queries

Try to keep the rules for media queries close to the rules related to them, and don’t put them together in a separate style file or at the bottom of the document, which only makes it easier for people to forget them later.

.element{... }.element-avatar{... }@media (min-width: 480px) {
    .element{... }.element-avatar{... }}Copy the code

12)Less relevant

Each module should have a separate less, then each outermost parent className should be written first, and all child Node styles should be written inside to avoid naming conflicts. Such as

//out: false
.parent-name{
    
    .child-name{... }... }Copy the code

@import imported files do not need ending ‘.less’

The nesting of LESS cannot exceed five layers.

The rule of not being available;

Element selectors are lowercase;

Remove the 0 in front of the decimal point;

Remove unnecessary decimal points and trailing zeros from numbers;

Attribute value ‘0’ is not followed by a unit;

Different prefixes for the same attribute should be aligned vertically, as shown on the right;

Standard attributes without prefixes should be written after prefixed attributes;

Do not have duplicate attributes in the same rule. It does not matter if the repeated attributes are contiguous.

Don’t have two rules in the same file;

With the border: 0; Instead of the border: none; ;

Don’t have more than 3 layers of CSS selectors;

Use the ‘*’ selector as little as possible.

/* not good */
.element{}/* not good */
LI{... }/* good */
li{... }/* not good */
.element {
    color: rgba(0.0.0.0.5);
}

/* good */
.element {
    color: rgba(0.0.0.5);
}

/* not good */
.element {
    width: 50.0 px.;
}

/* good */
.element {
    width: 50px;
}

/* not good */
.element {
    width: 0px;
}

/* good */
.element {
    width: 0;
}

/* not good */
.element {
    border-radius: 3px;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;

    background: linear-gradient(to bottom, #fff 0.#eee 100%);
    background: -webkit-linear-gradient(top, #fff 0.#eee 100%);
    background: -moz-linear-gradient(top, #fff 0.#eee 100%);
}

/* good */
.element {
    -webkit-border-radius: 3px;
       -moz-border-radius: 3px;
            border-radius: 3px;

    background: -webkit-linear-gradient(top, #fff 0.#eee 100%);
    background:    -moz-linear-gradient(top, #fff 0.#eee 100%);
    background:         linear-gradient(to bottom, #fff 0.#eee 100%);
}

/* not good */
.element {
    color: rgb(0.0.0);
    width: 50px;
    color: rgba(0.0.0.5);
}

/* good */
.element {
    color: rgb(0.0.0);
    color: rgba(0.0.0.5);
}
Copy the code

5 JavaScript

1) the indentation

Use soft TAB (4 Spaces).

var x = 1,
    y = 1;

if (x < y) {
    x += 10;
} else {
    x += 1;
}
Copy the code

2) a semicolon

A semicolon should be added in the following cases:

  • Variable declarations
  • expression
  • return
  • throw
  • break
  • continue
  • do-while
/* var declaration */
var x = 1;

/* expression statement */
x++;

/* do-while */
do {
    x++;
} while (x < 10);
Copy the code

3) the blank space

Spaces are not required in the following cases:

  • Object after the property name
  • Prefixes unary operator after
  • Suffix before unary operator
  • Function call before parentheses
  • Do not precede the ‘(‘ in function declarations or expressions
  • Array after ‘[‘ and before ‘]’
  • Object after ‘{‘ and before ‘}’
  • Operators ‘(‘ after and ‘)’ before

Spaces are required in the following cases:

  • Binary operator before and after
  • The ternary operator ‘? Before and after: ‘
  • Code block ‘{‘ before
  • Before the following keywords:else.while.catch.finally
  • After the following keywords:if.else.for.while.do.switch.case.try.catch.finally.with.return.typeof
  • Single-line comments after ‘//’ (if single-line comments are the same as code, ‘//’ is also required), multi-line comments after ‘*’
  • Object before the property value
  • For loop, a semicolon followed by a space, and a comma followed by a space if there are more than one preconditions
  • In function declarations and expressions, always precede the ‘{‘ with a space
  • Between the parameters of a function
// not good
var a = {
    b :1
};

// good
var a = {
    b: 1
};

// not good
++ x;
y ++;
z = x?1:2;

// good
++x;
y++;
z = x ? 1 : 2;

// not good
var a = [ 1.2 ];

// good
var a = [1.2];

// not good
var a = ( 1+2) *3;

// good
var a = (1 + 2) * 3;

// no space before '(', one space before '{', one space between function parameters
var doSomething = function(a, b, c) {
    // do something
};

// no space before '('
doSomething(item);

// not good
for(i=0; i<6; i++){ x++; }// good
for (i = 0; i < 6; i++) {
    x++;
}
Copy the code

4) a blank line

Blank lines are required in the following cases:

  • After a variable is declared (blank lines are not required when the variable is declared on the last line of the code block)
  • Before the comment (blank lines are not required when the comment is on the first line of the code block)
  • After a block of code (no blank lines in function calls, arrays, objects)
  • Leave a blank line at the end of the file
// need blank line after variable declaration
var x = 1;

// not need blank line when variable declaration is last expression in the current block
if (x >= 1) {
    var y = x + 1;
}

var a = 2;

// need blank line before line comment
a++;

function b() {
    // not need blank line when comment is first line of block
    return a;
}

// need blank line after blocks
for (var i = 0; i < 2; i++) {
    if (true) {
        return false;
    }

    continue;
}

var obj = {
    foo: function() {
        return 1;
    },

    bar: function() {
        return 2; }};// not need blank line when in argument list, array, object
func(
    2.function() {
        a++;
    },
    3
);

var foo = [
    2.function() {
        a++;
    },
    3
];

var foo = {
    a: 2.b: function() {
        a++;
    },
    c: 3
};
Copy the code

5) a newline

At the end of a line break there must be a ‘,’ or operator;

Line breaks are not required in the following cases:

  • After the following keywords:else.catch.finally
  • Code block ‘{‘ before

Line breaks are required in the following cases:

  • Code blocks ‘{‘ after and ‘}’ before
  • After the variable is assigned
// not good
var a = {
    b: 1
    , c: 2
};

x = y
    ? 1 : 2;

// good
var a = {
    b: 1.c: 2
};

x = y ? 1 : 2;
x = y ?
    1 : 2;

// no need line break with 'else', 'catch', 'finally'
if (condition) {
    ...
} else{... }try{... }catch (e) {
    ...
} finally{... }// not good
function test()
{... }// good
function test() {... }// not good
var a, foo = 7, b,
    c, bar = 8;

// good
var a,
    foo = 7,
    b, c, bar = 8;
Copy the code

6) One-line comments

A double slash must be followed by a space;

Indent the same as the next line of code;

Can be at the end of a line of code, separated by a space from the code.

if (condition) {
    // if you made it here, then all security checks passed
    allowed();
}

var zhangsan = 'zhangsan'; // one space after code
Copy the code

7) Multi-line comments

At least three lines with ‘*’ followed by a space, as shown on the right;

It is recommended to be used in the following situations:

  • Difficult code snippets
  • There may be incorrect code snippets
  • Browser-specific HACK code
  • Code with strong business logic correlation
/* * one space after '*' */
var x = 1;
Copy the code

8)Documentation comments

Please refer to usEJsDoc and JSDoc Guide for tags @param, @Method, etc.

It is recommended to be used in the following situations:

  • All of the constants
  • All the functions
  • All the classes
/** * @func * @desc A function with arguments * @param {string} a - parameter a * @param {number} b=1 - Parameter b default value is 1 * @param {string} c=1 - There are two supported values for parameter C: </br>1 - x</br>2 - XX * @param {object} d - Parameter D is an object * @param {string} d.e - The e attribute of parameter D * @param {string} d.f - Parameter d f attribute * @param {object[]} g - parameter g is an object array * @param {string} g.h - parameter g array h attribute * @param {string} g.i - parameter g array I attribute * @param {string} [j] - Argument j is an optional argument */function foo(a, b, c, d, g, j) {
    ...
}
Copy the code

9) quotes

Use single quotation marks for the outermost layer.

// not good
var x = "test";

// good
var y = 'foo',
    z = '<div id="test"></div>';
Copy the code

10) Variable naming

  • Standard variables are named in camel case (in addition to the attributes of the object, the main consideration is the data returned by CGI)
  • ‘ID’ is all uppercase in the variable name
  • ‘URL’ is all uppercase in the variable name
  • ‘Android’ capitalizes the first letter in the variable name
  • ‘iOS’ is the first letter in the variable name, followed by two uppercase letters
  • Constants are all uppercase and underlined
  • Constructor, uppercase the first letter
  • Jquery objects must be named starting with ‘$’
var thisIsMyName;

var goodID;

var reportURL;

var AndroidVersion;

var iOSVersion;

var MAX_COUNT = 10;

function Person(name) {
    this.name = name;
}

// not good
var body = $('body');

// good
var $body = $('body');
Copy the code

11) Variable declaration

All variable declarations in a function scope refer to the header of the function as much as possible. Use a single var declaration.

function doSomethingWithItems(items) {
    // use one var
    var value = 10,
        result = value + 10,
        i,
        len;

    for (i = 0, len = items.length; i < len; i++) {
        result += 10; }}Copy the code

12) function

In function declarations and expressions, there is no space before ‘(‘, but there must be a space before ‘{‘;

Function calls do not require Spaces before parentheses;

Immediate functions must be wrapped in parentheses;

Do not name inline functions;

Arguments are separated by ‘, ‘, and note that there is a space after the comma.

// no space before '(', but one space before'{'
var doSomething = function(item) {
    // do something
};

function doSomething(item) {
    // do something
}

// not good
doSomething (item);

// good
doSomething(item);

// requires parentheses around immediately invoked function expressions
(function() {
    return 1; }) ();// not good
[1.2].forEach(function x() {... });// good
[1.2].forEach(function() {... });// not good
var a = [1.2.function a() {... }];// good
var a = [1.2.function() {... }];// use ', ' between function parameters
var doSomething = function(a, b, c) {
    // do something
};
Copy the code

13) Arrays, objects

Object attribute names do not need to be quoted;

Write objects indented, not on a single line;

Arrays and objects should not end with commas.

// not good
var a = {
    'b': 1
};

var a = {b: 1};

var a = {
    b: 1.c: 2};// good
var a = {
    b: 1.c: 2
};
Copy the code

14) brackets

Braces must follow the following keywords (even if the block is only one line) : if, else,for, while, do, switch, try, catch, finally, with.

// not good
if (condition)
    doSomething();

// good
if (condition) {
    doSomething();
}
Copy the code

15)null

Applicable scenarios:

  • Initialize a variable that may be assigned as an object in the future
  • Compare with an already initialized variable
  • Call to a function that takes an object as an argument
  • The return value of a function that returns an object

Not applicable scenarios:

  • Do not use null to determine if a function is called with or without arguments
  • Do not compare with uninitialized variables
// not good
function test(a, b) {
    if (b `= null) { // not mean b is not supply ... } } var a; if (a `= null) {... }// good
var a = null;

if (a `= null) { ... }Copy the code

16)undefined

Never use undefined directly for variable judgments;

Use typeof and the string ‘undefined’ to determine variables.

// not good
if (person `= undefined) { ... } // good if (typeof person `= 'undefined') {... }Copy the code

17)jshint

With the ‘=’, ‘! ‘Instead of ‘, ‘! = ‘;

HasOwnProperty = hasOwnProperty;

Do not add methods to the prototype of built-in objects, such as Array, Date;

Do not declare a variable in the inner scope code and then access a variable of the same name in the outer scope.

Do not use variables before declaring them;

Don’t just use constructors in a line of code; assign them to a variable;

Do not declare variables of the same name in the same scope;

Do not put parentheses in unnecessary places, for example: delete(a.b);

Do not use undeclared variables (global variables need to be added to the globals property of the.jshintrc file);

Don’t declare variables and leave them unused;

Don’t assign values where comparisons should be made;

The debugger should not appear in submitted code;

Do not have empty elements in the array;

Do not declare functions inside loops;

Do not use constructors like this, for example: new function () {… }, the new Object;

// not good
if (a ` 1) { a++; } // good if (a `= 1) {
    a++;
}

// good
for (key in obj) {
    if (obj.hasOwnProperty(key)) {
        // be sure that obj[key] belongs to the object and was not inherited
        console.log(obj[key]); }}// not good
Array.prototype.count = function(value) {
    return 4;
};

// not good
var x = 1;

function test() {
    if (true) {
        var x = 0;
    }

    x += 1;
}

// not good
function test() {
    console.log(x);

    var x = 1;
}

// not good
new Person();

// good
var person = new Person();

// not good
delete(obj.attr);

// good
delete obj.attr;

// not good
if (a = 10) {
    a++;
}

// not good
var a = [1.2.3];

// not good
var nums = [];

for (var i = 0; i < 10; i++) {
    (function(i) {
        nums[i] = function(j) {
            return i + j;
        };
    }(i));
}

// not good
var singleton = new function() {
    var privateVar;

    this.publicMethod = function() {
        privateVar = 1;
    };

    this.publicMethod2 = function() {
        privateVar = 2;
    };
};
Copy the code

18) miscellaneous

Don’t mix tabs and Spaces;

Don’t use multiple tabs or Spaces in one place;

Use ‘LF’ for line breaks;

References to context this can only be named ‘_this’, ‘that’, or ‘self’;

No whitespace characters at the end of the line;

The switch’s falling through and no default cases must be specified in a comment.

Empty code blocks are not allowed.

// not good
var a   = 1;

function Person() {
    // not good
    var me = this;

    // good
    var _this = this;

    // good
    var that = this;

    // good
    var self = this;
}

// good
switch (condition) {
    case 1:
    case 2:... break;case 3:...// why fall through
    case 4. break;// why no default
}

// not good with empty block
if (condition) {

}
Copy the code

EditorConfig for VS Code generates. EditorConfig files

root = true

[*]
indent_style = space
indent_size = 4
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false
Copy the code

To be continued