General convention


General Conventions

Comments

Principles

  • As short as possible (If not necessary, do not Add comments): Try to improve the clarity and readability of the code itself.
  • As long as necessary (if necessary, try to be as detailed as possible): Reasonable comments, blank line formatting, etc. can make the code easier to read and more beautiful.

Single-line comments

must occupy one line. // is followed by a space, and the indentation is consistent with the commented code on the next line.

Multi-line comments

Avoid using multi-line comments like /*...*/. When there are multiple lines of comment content, use multiple single-line comments.

Function/method comments

  1. Function/method comments must contain function descriptions, and comment identifiers must be used when there are parameters and return values. ;
  2. Parameter and return value annotations must contain type information and description;
  3. When the function is an internal function and is not accessible from the outside, the @inner identifier can be used;
/**
 * 函数描述
 *
 * @param {string} p1 参数1的说明
 * @param {string} p2 参数2的说明,比较长
 *     那就换行了.
 * @param {number=} p3 参数3的说明(可选)
 * @return {Object} 返回值描述
 */
function foo(p1, p2, p3) {
    var p3 = p3 || 10;
    return {
        p1: p1,
        p2: p2,
        p3: p3
    };
}

File comments

File comments are used to tell readers who are not familiar with this code what is contained in this file. The general contents of the file, its author, dependencies and compatibility information should be provided. As follows:

/**
 * @fileoverview Description of file, its uses and information
 * about its dependencies.
 * @author user@meizu.com (Firstname Lastname)
 * Copyright 2009 Meizu Inc. All Rights Reserved.
 */

Name

variable, using Camel nomenclature.

var loadingModules = {};

Private properties, variables and methodsBegin with an underscore _.

var _privateMethod = {};

Constant, use all capital letters and underscores to separate words.

var HTML_ENTITY = {};
  1. Function, using Camel nomenclature.
  2. The parameters of the function use Camel nomenclature.
function stringFormat(source) {}

function hear(theBells) {}
  1. Class, use Pascal nomenclature
  2. Class’s method/attribute, use Camel nomenclature
function TextNode(value, engine) {
    this.value = value;
    this.engine = engine;
}

TextNode.prototype.clone = function () {
    return this;
};
  1. Enumeration variables Use Pascal nomenclature.
  2. Enumeration attributes are named using all uppercase letters and underscores between words.
var TargetState = {
    READING: 1,
    READED: 2,
    APPLIED: 3,
    READY: 4};

Abbreviation consisting of multiple words. In naming, the case of all letters and the first letter are maintained according to the current nomenclature and the position of occurrence. consistent.

function XMLParser() {}

function insertHTML(element, html) {}

var httpRequest = new HTTPRequest();

Naming syntax

Class name, use nouns.

function Engine(options) {}

Function name, use verb-object phrase.

function getStyle(element) {}

boolean Variables of type start with is or has.

var isReady = false;var hasMoreCommands = false;

Promise object is expressed in the progressive tense of the verb-object phrase.

var loadingData = ajax.get('url');
loadingData.then(callback);

Interface naming convention

  1. Highly readable and well-known;
  2. Try not to conflict with the existing habits of the jQuery community;
  3. Try to Write it all. No abbreviations are used unless agreed upon in the list below; (variables are designed to express clearly, uglify will complete the compression volume work)

QQ截图20170206113712.png

True and False Boolean expressions

Type detection preferentially uses typeof. Object type detection uses instanceof. Detection of null or undefined uses == null.

The following Boolean expressions all return false:

  • null
  • undefined
  • '' empty string
  • 0 Number 0

But be careful with the following, they can all return true:

  • '0' String 0
  • [] Empty array
  • {} Empty object

Do not use for-in loop on Array

For-in loop is only used for traversal of object/map/hash , Using for-in loops on Array sometimes causes errors. Because it does not traverse from 0 to length - 1, but all key values ​​that appear in the object and its prototype chain.

// Not recommended
function printArray(arr) {
  for (var key in arr) {
    print(arr[key]);
  }
}

printArray([0,1,2,3]);  // This works.

var a = new Array(10);
printArray(a);  // This is wrong.

a = document.getElementsByTagName('*');
printArray(a);  // This is wrong.

a = [0,1,2,3];
a.buhu = 'wine';
printArray(a);  // This is wrong again.

a = new Array;
a[3] = 3;
printArray(a);  // This is wrong again.

// Recommended
function printArray(arr) {
  var l = arr.length;
  for (var i = 0; i < l; i++) {
    print(arr[i]);
  }
}

Binary and ternary operators

Operators are always written on the previous line to avoid implicit insertion of semicolons causing unexpected problems.

var x = a ? b : c;

var y = a ?
    longButSimpleOperandB : longButSimpleOperandC;

var z = a ?
        moreComplicatedB :
        moreComplicatedC;

. The same is true for operators:

var x = foo.bar().
    doSomething().
    doSomethingElse();

Conditional (ternary) operator (?:)

The ternary operator is used for substitution if conditional statement. The

// Not recommended
if (val != 0) {
  return foo();
} else {
  return bar();
}

// Recommended
return val ? foo() : bar();

&& and ||

binary Boolean operators are shortcircuitable and will only evaluate to the last item when necessary.

// Not recommended
function foo(opt_win) {
  var win;
  if (opt_win) {
    win = opt_win;
  } else {
    win = window;
  }
  // ...
}

if (node) {
  if (node.kids) {
    if (node.kids[index]) {
      foo(node.kids[index]);
    }
  }
}

// Recommended
function foo(opt_win) {
  var win = opt_win || window;
  // ...
}

var kid = node && node.kids && node.kids[index];
if (kid) {
  foo(kid);
}