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

Comments ใน JavaScript คำอธิบาย

JavaScript รองรับ Comments แบบ C-style และ C++-style:

ประเภท Comments

ประเภทไวยากรณ์คำอธิบาย
Single-line// commentจนจบบรรทัด ถูก Ignore โดย JS
Multi-line/* comment */หลายบรรทัด ไม่ซ้อนกันได้ (Nesting)
HTML Open<!--JS รับเป็น Single-line Comment (Legacy)
HTML Close-->JS ไม่จดจำ ต้องเขียน //-->

ตัวอย่าง

<script>
  <!--
  // This is a comment. คล้าย C++

  /*
   * This is a multi-line comment in JavaScript
   * คล้าย C Programming
   */

  //-->
</script>

JSDoc (Documentation Comments)

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

Special Comment Tags

  • // TODO: งานที่ต้องทำต่อ
  • // FIXME: บั๊กที่ต้องแก้
  • // NOTE: หมายเหตุสำคัญ
  • // HACK: วิธีแก้ชั่วคราว/ไม่สวย
  • // DEPRECATED: ล้าสมัย จะลบในอนาคต

Best Practices

  • Comment Why (ทำไม) ไม่ใช่ What (ทำอะไร - โค้ดบอกเองได้)
  • อัปเดต Comment เมื่อแก้โค้ด (Outdated Comment สิ้นเปลืองกว่าไม่มี)
  • ใช้ JSDoc สำหรับ Public API
  • หลีกเลี่ยง Comment โค้ดมากเกินไป → Refactor ให้โค้ดอ่านง่ายแทน