Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

มาตรฐานการเขียน Comment ฟังก์ชันใน JavaScript (JSDoc)

มาตรฐานที่ใช้กันอย่างกว้างขวางคือ 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 ถ้าสำเร็จ
@throwsError ที่อาจโยน@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-jsdoc rule
  • Documentation Generators: jsdoc.app, TypeDoc, documentation.js

ประโยชน์

  • IDE แสดง hint ขณะพิมพ์ (IntelliSense)
  • Generate API Documentation อัตโนมัติ
  • Type checking ใน JS (ผ่าน TypeScript / VS Code)
  • ทีมเข้าใจ API ได้ง่ายขึ้น