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

JavaScript มีมาตรฐาน Comment สำหรับ Functions ไหม

ใช่ ใช้ JSDoc เป็นมาตรฐาน De Facto สำหรับ Document Functions ใน JavaScript/TypeScript

JSDoc Format

/**
 * Adds two numbers.
 * @param {number} a - First number
 * @param {number} b - Second number
 * @returns {number} Sum of a and b
 */
function sum(a, b) {
  return a + b;
}

Tags พบบ่อย

Tagคำอธิบายตัวอย่าง
@paramพารามิเตอร์@param {string} name - User name
@returns / @returnค่าที่คืน@returns {boolean} True if valid
@throwsError ที่อาจโยน@throws {Error} If invalid
@typeชนิดตัวแปร@type {number}
@seeอ้างอิงอื่น@see https://example.com
@deprecatedล้าสมัย@deprecated Use newFunc()
@exampleตัวอย่างใช้งาน@example add(1,2) // 3
@authorผู้เขียน@author John Doe
@versionเวอร์ชัน@version 1.0.0

Type Expressions

@param {string} name           // Primitive
@param {string[]} tags          // Array of strings
@param {Object} options         // Object
@param {Object.} map // Object with string keys, number values
@param {Function} callback      // Function
@param {(a: number, b: number) => number} fn // Function Signature (Closure Compiler)
@param {...number} rest         // Rest Parameters
@param {?string} optional       // Nullable (Closure)
@param {string=} optional       // Optional (Closure)
@param {string} [optional]      // Optional (JSDoc)

Tools รองรับ

  • VS Code: IntelliSense จาก JSDoc อัตโนมัติ
  • TypeScript: เข้าใจ JSDoc (// @ts-check)
  • ESLint: require-jsdoc, valid-jsdoc
  • Documentation Generators: jsdoc, typedoc, documentation.js

แนะนำ: เขียน JSDoc สำหรับ Public API/Exported Functions ใช้ TypeScript สำหรับ Type Safety แทน JSDC Types ในโปรเจกต์ใหญ่