JSDoc作用
我们都知道js是门弱类型的语言,所以,为了增强代码的可读性,提高js的代码规范,可以选择使用JSDoc进行代码的注释,有了更多类型描述,例如参数类型,函数的返回值类型等等这些的类型描述,在进行开发时会带来很大的便捷,在这基础上稍做扩展,就可以用于代码提示和语法分析,同时JSDoc也可以导出API文档
了解基础的JSDoc的使用
对于复杂的JSDoc的使用,本文就不做介绍了,这里推荐下可以使用Vs code 的插件 Document This , 利用它可以快速生成注释 .本文的主要目的是想要介绍些入门的基础JSDoc 使用语法
标签的使用
通过书写标签,对js解析引擎确定变量类型有一定的帮助
| 标签 | 介绍 | 使用 |
|---|---|---|
| alias | 给一个变量或者函数指定一个别名,代码提示时会提示该别名 | @alias aliasName |
| constructor | 使用@constructor可以标识一个函数是构造函数 | @constructor |
| description | 使用@description可以在代码提示时显示被描述变量或者函数的描述信息 | @description 描述内容 |
| example | 使用@example可以提示代码示例。 | @example 示例内容 |
| extends | 使用@extends用于标识继承于某个类型 | @extends {Type} |
| param | 使用@param可以描述一个函数的参数以及参数类型 | `@param {Type[,Type,…]} ParameterName=[Value1 |
| property | 使用@property可以描述一个对象的属性 | @property {Type[,Type,...]} propertyName 属性描述 |
| return | 使用@return可以描述一个对象的属性 | @return {Type[,Type,...]} |
| type | 使用@type可以定义某个变量的类型 | @type {Type[,Type,...]} |
标签的代码示例
extends
class Animal { /** * @description 这是一个构造函数 * @example * var animal = new Animal('恐龙',1000); * @constructor */ constructor(name,weight){ this.name = name; this.weight = weight; } say(){ }}/** * @extends {Animal} */class Dog extends Animal{ constructor(name,weight){ super(name,weight); } say (){ console.log(this.name+":wang wang wang ..."); }}
param
/** * 这是一个方法描述 * @param {String} method = [get|post] 可选值域包括get和post,get是直接请求,post是提交数据 */function Request(method) {}
return
/** * @return {HTMLDocument} */function getDocument() { //some code}
property
/** * @property {IDString} id id元素 * @property {ClassString} classNames class样式 */var htmlOptions = { id:null, classNames:null}htmlOptions.id = "123";htmlOptions.classNames = "arrow area"
type
/** * @type {IDString} */var htmlId = null;htmlId = "123";
类型语法
单一类型
这里定义一个类型为Document的变量/** * @type {Document} */var foo = null;
多个类型
这里定义一个类型为Document,HTMLElement的变量/** * @type {Document,HTMLElement} */var foo = null;
函数类型
//这里定义一个参数为Event的回调函数/** * @param {Function(Event)} callback */function testCallBack(callback){}//这里定义一个返回类型是参数为IDString返回值为HTMLElement的函数。/** * @return {Function(IDString):HTMLElement} */function testFunctionReturn(){ return foo;}var rFunc = testFunctionReturn();rFunc('id').getElementsByClassName('classA');
最后
本文的绝大部分借鉴了html5plus官网上的这篇 文章,更多详细信息可以去查看JSDoc的官方文档,本文只做个入门的参考