JavaScript代碼註釋範例

JavaScript代碼註釋範例

作爲一個有情懷的Coder,最近收集了一下JavaScript代碼註釋範例,但願可以幫助你們擼得一手妖媚而又放蕩的Bug。

普通註釋

單行註釋

使用 // 做爲單行註釋。javascript

單行註釋符後與註釋內容保留一個空格。html

//bad comments
// good comments

單行註釋須要在說明的代碼之上另起一行,而且在註釋前插入空行。java

function isType(content, expect) {

    // good
    // Using Object.prototype.toString to judge data types.
    let type = Object.prototype.toString.call(content).replace(/\[object\s|\]/g, '');

    return type === expect;
}
// bad
console.log(isType('hello', 'String'));       // return true

帶有 // FIXME:// TODO: 的前綴的註釋能夠幫助其餘開發者快速瞭解這是一個須要複查的問題,或是給須要實現的功能提供一個解決方式。這將有別於常見的註釋,由於它們是可操做的。使用 FIXME -- need to figure this out 或者 TODO -- need to implementnode

使用 // FIXME: 標註問題。react

class Calculator {
    constructor() {
        // FIXME: shouldn't use a global here
        total = 0;
    }
}

使用 // TODO: 標註問題的解決方式。jquery

// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( newContext && (elem = newContext.getElementById( m )) &&
    contains( context, elem ) &&
    elem.id === m ) {

    results.push( elem );
    return results;
}

多行註釋

多行註釋星號 * 對齊,而且註釋內容不要寫在起始符號 /**與結束符號 */ 所在行。git

// bad
/* matches from matchExpr["CHILD"]
  1 type (only|nth|...)
   2 what (child|of-type)
*/

// good
/* 
    matches from matchExpr["CHILD"]
    1 type (only|nth|...)
    2 what (child|of-type)
 */

文件註釋(多行註釋)

使用 /* ... */ 做爲文件註釋。github

文件註釋主要包含:概要介紹、版本信息、版權聲明、開源協議、修改時間等說明內容。api

React.js數組

/** @license React v16.4.0
 * react.development.js
 *
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

jQuery.js

/*!
 * jQuery JavaScript Library v3.3.1
 * https://jquery.com/
 *
 * Includes Sizzle.js
 * https://sizzlejs.com/
 *
 * Copyright JS Foundation and other contributors
 * Released under the MIT license
 * https://jquery.org/license
 *
 * Date: 2018-01-20T17:24Z
 */

開源項目的開發版本生產版本中都會保留文件註釋,且必須對引用的其餘開源代碼進行說明。

文檔註釋(多行註釋)

使用 /** ... */ 做爲文檔API註釋。包含描述與指定全部參數和返回值的類型和值的註釋標籤

/**
 * Maps children that are typically specified as `props.children`.
 *
 * See https://reactjs.org/docs/react-api.html#react.children.map
 *
 * The provided mapFunction(child, key, index) will be called for each
 * leaf child.
 *
 * @param {?*} children Children tree container.
 * @param {function(*, int)} func The map function.
 * @param {*} context Context for mapFunction.
 * @return {object} Object containing the ordered map of results.
 */
function mapChildren(children, func, context) {

  if (children == null) {
    return children;
  }

  var result = [];
  mapIntoWithKeyPrefixInternal(children, result, null, func, context);

  return result;
}

經常使用註釋標籤

@param 指定參數的名稱。您還能夠包含參數的數據類型,使用大括號括起來,和參數的描述。

/**
 * @param content
 */

註釋變量名 和 變量類型

/**
 * @param {String} type
 */

註釋變量名、變量類型 和 變量說明

/**
 * @param {String} attrs Pipe-separated list of attributes
 */

連字符可使註釋閱讀友好

參數變量名與參數說明之間使用連字符 -

/**
 * @param {object} partialState - Next partial state to be merged with state.
 */

對象參數屬性描述

描述一個對象參數的屬性

/**
 * @param {Object} employee - The employee who is responsible for the project.
 * @param {string} employee.name - The name of the employee.
 * @param {string} employee.department - The employee's department.
 */

一樣,能夠聯想到若是假如 employee 參數是一個數組,這個數組中包含 namedepartment 元素,那麼能夠這麼描述。

描述參數的屬性值在數組中

/**
 * Assign the project to a list of employees.
 * @param {Object[]} employees - The employees who are responsible for the project.
 * @param {string} employees[].name - The name of an employee.
 * @param {string} employees[].department - The employee's department.
 */

可選參數和默認值

JSDoc可選參數

/**
 * @param {string} key - Key to be escaped.
 */

JSDoc可選參數和默認值

/**
 * @param {Number} [index=0] - Somebody's name.
 */

Google Closure Compiler 可選參數

/**
 * @param {string=} somebody - Somebody's name.
 */

多種類型參數

下面的例子演示瞭如何使用類型的表達式來表示一個參數能夠接受多種類型(或任何類型),還有一個參數能夠被屢次使用。

/**
 * @param {(string|string[])} [somebody=John Doe] - Somebody's name, or an array of names.
 */

容許任何類型

/**
 * @param {*} component - A component that could contain a manual key.
 */

可重複使用的參數

全部可變參數都是數字

/**
 * @param {...number} num - A positive or negative number.
 */

管道字符 | 用來鏈接聯合類型,聯合類型用來代表參數能夠有多個類型

/** 
 * @param {string|null|undefined} str 
 */

由於參數是否非空很常見,所以有一個快捷方式用來標明聯合類型是否包含 null

/** 
 * @param {?string} str1 is a string or null 
 * @param {?string|undefined} str2 is a string, null, or undefined. The ? 
 *     prefix does not include undefined, so it must be included explicitly. 
 */

除了基本類型的全部類型,如Object,Array和HTMLDocument默認均可覺得空,這些類型統稱爲對象類型,所以 ? 前綴對對象類型是多餘的

/** 
 * @param {Document} doc1 is a Document or null because object types are nullable by default. 
 * @param {?Document} doc2 is also a Document or null. 
 */

若是要聲明一個非空對象對開,能夠用 ! 前綴

/** 
 * @param {!Array} array must be a non-null Array 
 * @param {!Array|undefined} maybeArray is an Array or undefined, but 
 *     cannot be null. 
 */

儘管一個方法中能夠有任意多個可選參數,可是可選參數不該該出如今必須參數以前,若是出如今以前,代碼必須寫成以下形式

/** 
 * @param {string=} title Defaults to 'New Spreadsheet'. 
 * @param {string} author 
 */

大量的可靠參數,最好將其它移到一個必須的對象參數中

/**  
 * @param {{author: (string|undefined), title: (string|undefined), numRows: (number|undefined)  
 */

不定數量參數

Closure不定數量參數

/** 
 * @param {string} category 
 * @param {...} purchases 
 * @return {number} 
 */

註釋函數類型值的可選和可變參數

/** 
 * @param {function(string, string=)} ……
 * @param {function(string, ...[number]): number} ……
 */

回調函數

使用 @callback 標籤來定義回調類型,回調類型包含到 @param 中。

/**
 * This callback type is called `requestCallback` and is displayed as a global symbol.
 *
 * @callback requestCallback
 * @param {number} responseCode
 * @param {string} responseMessage
 */

/**
 * Does something asynchronously and executes the callback on completion.
 * @param {requestCallback} cb - The callback that handles the response.
 */

@return / @returns 返回值的類型和描述

/**
 * @return {object} Object containing the ordered map of results.
 * @return {!number} The number of children in this subtree.
 */

或者

/**
 * @returns {boolean} True if mounted, false otherwise.
 * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
 */

更多示例

/**
 * @param {?Function(*, Boolean)} callback - To invoke upon traversing each child.
 * @param {String|Number} ref
 * @param {?*} children - Children tree container.
 * @param {Element|Object=} context
 * @param {!ArrayLike<Element>} nodes
 * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
 */

/**
 * @param {?*} children - Children tree container.
 * @param {!string} nameSoFar - Name of the key path so far.
 * @param {!function} callback - Callback to invoke with each child found.
 * @return {!number} The number of children in this subtree.
 */

更多請參考

如下網站爲本文參考,歡迎留言糾正。

YUIDoc Syntax Reference
@use JSDoc
Closure javascript註解
Airbnb JavaScript Style Guide() { - 註釋
原文Airbnb JavaScript Style Guide() {
js/javascript代碼註釋規範與示例
Js註釋

相關文章
相關標籤/搜索