有時往往我們需要建一個文檔來記錄js中的一些代碼注釋,比如一些公共的函數,又或者一些類,在團隊合作中,文檔接口也是必不可少的,傳統的方式多少有些不便,這里介紹一個工具,它叫JSDOC,它可以用來將注釋生成文檔。
雖然說是說它可以把注釋生成文檔,但是也不是什么注釋都可以的,我們需要按照它的規范來寫。
首先我們通過npm來下載它。
npm install jsdoc -g
JSDOC的格式是這樣的。
/**
* 兩個數相加
* @param {number} num1 加法
* @param {number} num2 被加
* @returns {number} 和*/
function add(num1,num2){
return num1 + num2;
}
首先注釋得以/**開始,結束以*/結束。
@:在jsdoc中有一定的作用,就是它有一套標簽規則。如:
@param {type} n1 description
param:表示函數參數 {類型} 參數值 描述
@returns {type} description
returns:返回值 描述
還有很多。
生成jsdoc文檔:cmd里面執行jsdoc xx.js
會在當前目錄下生成一個out目錄,里面有一個index.html,打開可以看到生成的結果。
看見沒,還是很清楚的。
里面還有一個Tank構造函數其中代碼是這樣的。
/**
* 坦克類
* @constructor
* @param {number} x 坐標X
* @param {number} y 坐標Y
* @param {number} dire 方向
* @param {array} colors 一組顏色
*/
function Tank(x,y,dire,colors){
this.x = x;
this.y = y;
// 速度
this.steep = 5;
// 方向
this.dire = dire;
// 坦克顏色
this.colors = colors;
// 移動方向
this.moveUp = function(){
this.y-= this.steep;
this.dire = 0;
};
this.moveRight = function(){
this.x+= this.steep;
this.dire = 1;
};
this.moveDown = function(){
this.y+= this.steep;
this.dire = 2;
};
this.moveLeft = function(){
this.x-= this.steep;
this.dire = 3;
};
}
@constructor表示一個構造器,你看上面的截圖就可以很清楚的看到它的結果是什么樣子了。
這上面介紹的是幾個比較常用的,當然還有很多方法,這里就不一一介紹了,可以看官方文檔或者搜索一下相關的教程,這里只是給大家入個門。