JSDoc is to mark variable types, function parameters, return values, etc. in the comments of the JS code in a specific format. This can avoid passing errors or fewer parameters when calling the function, improving the robustness of the code, and reducing bugs; Coupled with the support of the editor, the coding efficiency can be greatly improved.
For example, the following example,
Because we have marked the pd
, when calling pd
, the editor can easily prompt what methods are on this object.
We looked at the official JSDoc document and found that a lot of functions are listed, but in fact, there are only a few commonly used functions. It only takes a few minutes to master the following methods to greatly improve the editing experience of writing code. .
JSDoc grammatically requires /**
starting */
.
Declare the type of the parameter
@param {参数的类型} 参数的名 注释
As shown in the figure, when we define a function, enter /**
above the function and press Enter. The editor will automatically add relevant variable names and other information for us. We only need to fill in the parameter type. .
After writing the type, use it inside the function, the editor will prompt the corresponding method and attribute;
When calling a function, the editor will also parse the content we have written in JSDoc, prompting the type of parameters that need to be passed in and the comments of the parameters.
the type shown on FIG addition
string
, there are boolean
, undefined
, null
type; and complex type, {key1:string,key2?:number}
; may also be combined with each other such string|number
the like which can be used typescript type
defined.
Declare the type of the return value
Use @returns
to specify the parameter type and return value type of the function
@returns {string}
E.g:
/**
*
* @param {string} id 注释注释注释
* @param {string} name 注释注释注释
* @returns {string}
*/
function getName(id, name) {
//name.
}
The effect of the call:
Declare the type of the variable
/**@type {string} */
var aaa=global.aaa
Effect picture:
Define a type
Sometimes, some types are more complicated and need to be used in many places. At this time, we can define a type for use in other places.
@typedef {类型} 类型名
For example, we define a type User with two attributes name and age respectively
/**@typedef {{name:string,age:number}} User */
It can also be written in this way:
/**
* @typedef {Object} User
* @property {string} name
* @property {number} age
*/
Used in the function definition:
Used elsewhere:
Define a complex type of function type:
/**@typedef {(a:string,b:string)=>void} FN */
Other examples, such as a certain attribute of the marked object, such as get
is a function, and the types of parameters in this function should be standardized:
Or like this:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。