มาตรฐานที่ใช้กันอย่างกว้างขวางคือ JSDoc ใช้บล็อกคอมเมนต์ /** ... */ พร้อมแท็ก (tags) เพื่ออธิบายฟังก์ชัน พารามิเตอร์ ค่าคืน และอื่นๆ
ตัวอย่างจากบทความ (JSDoc Format)
/**
* Adds two numbers
* @param {Number} num1
* @param {Number} num2
* @return {Number} sum
*/
function sum(num1, num2) {
return num1 + num2;
}
JSDoc Tags ที่ใช้บ่อย
| Tag | คำอธิบาย | ตัวอย่าง |
|---|---|---|
@param | พารามิเตอร์ | @param {string} name - ชื่อผู้ใช้ |
@returns / @return | ค่าที่คืน | @returns {boolean} true ถ้าสำเร็จ |
@throws | Error ที่อาจโยน | @throws {Error} ถ้า ID ไม่ถูกต้อง |
@example | ตัวอย่างการใช้งาน | @example add(1, 2) // 3 |
@deprecated | เลิกใช้แล้ว | @deprecated ใช้ newFunc() แทน |
@see | อ้างอิงอื่น | @see https://example.com |
@since | เวอร์ชันที่เพิ่ม | @since 1.2.0 |
@todo | งานค้าง | @todo optimize performance |
Type Expressions
// Primitive types
{string}, {number}, {boolean}, {null}, {undefined}, {symbol}, {bigint}
// Object types
{Object}, {Array}, {Function}, {Date}, {RegExp}, {Promise}
// Custom types
{User}, {User[]}, {Map}
// Union types
{string|number}, {(string|number)[]}
// Nullable/Optional
{?string} // string หรือ null
{string=} // optional (default undefined)
{string=} default // optional with default
// Function type
{function(string, number): boolean}
ตัวอย่างครบถ้วน
/**
* ค้นหาผู้ใช้จาก ID
* @param {string|number} userId - รหัสผู้ใช้ (รองรับ string หรือ number)
* @param {Object} [options] - ตัวเลือกเพิ่มเติม
* @param {boolean} [options.includeProfile=false] - รวมโปรไฟล์หรือไม่
* @param {string[]} [options.fields] - ฟิลด์ที่ต้องการ
* @returns {Promise} ข้อมูลผู้ใช้ หรือ null ถ้าไม่พบ
* @throws {ValidationError} ถ้า userId ไม่ถูกต้อง
* @example
* const user = await findUser(123, { includeProfile: true });
* @since 2.0.0
*/
async function findUser(userId, options = {}) {
// implementation
}
Class และ Method Documentation
/**
* User Service Class
* @class
*/
class UserService {
/**
* สร้าง instance ใหม่
* @constructor
* @param {Database} db - Database connection
*/
constructor(db) {
this.db = db;
}
/**
* ดึงข้อมูลผู้ใช้
* @param {string} id
* @returns {Promise}
*/
async getUser(id) {
// ...
}
}
เครื่องมือที่รองรับ JSDoc
- VS Code: IntelliSense, Hover tooltip, Go to Definition
- TypeScript: ใช้ JSDoc สำหรับ type checking (checkJs: true)
- ESLint:
require-jsdocrule - Documentation Generators: jsdoc.app, TypeDoc, documentation.js
ประโยชน์
- IDE แสดง hint ขณะพิมพ์ (IntelliSense)
- Generate API Documentation อัตโนมัติ
- Type checking ใน JS (ผ่าน TypeScript / VS Code)
- ทีมเข้าใจ API ได้ง่ายขึ้น