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

JavaScript Identifiers (ตัวระบุ) คืออะไร

JavaScript Identifiers คือ ชื่อที่ใช้ระบุ Variables, Functions, Parameters, Classes, Properties, Labels เหมือนภาษาอื่น (C, C++, Java)

ตัวอย่าง Identifier ที่ถูกต้อง

val
val1
result
userName
$price
_element
myFunction
PI

กฎการตั้งชื่อ (Naming Rules)

  1. ห้ามใช้ Reserved Keywords: break, case, catch, class, const, continue, debugger, default, delete, do, else, export, extends, false, finally, for, function, if, import, in, instanceof, new, null, return, super, switch, this, throw, true, try, typeof, var, void, while, with, yield และคำสงวนอนาคต (enum, implements, interface, package, private, protected, public, static)
  2. ตัวแรกต้องเป็น: ตัวอักษร (a-z, A-Z), Underscore (_), Dollar Sign ($) — ห้ามขึ้นต้นด้วยตัวเลข (0-9)
  3. ตัวต่อไปเป็นได้: ตัวอักษร, ตัวเลข, Underscore, Dollar Sign
  4. Case-Sensitive: name และ Name เป็นคนละตัวแปร
  5. Unicode: รองรับ Unicode Letter (ภาษาไทย, จีน, ฯลฯ) ได้ แต่ไม่แนะนำสำหรับโค้ดร่วมงาน
  6. ตัวอย่าง Invalid Identifiers

    5demo       // เริ่มต้นด้วยตัวเลข
    my-var      // มี Hyphen (-) - ใช้ camelCase แทน: myVar
    function    // Reserved Keyword
    class       // Reserved Keyword
    const       // Reserved Keyword

    Valid แต่ควรหลีกเลี่ยง

    _private      // Convention: Private (แต่ JS ไม่ enforce)
    $element      // Convention: jQuery/DOM Element
    __proto__     // Magic Property (หลีกเลี่ยง)
    constructor   // Property Name ปกติ แต่สับสนกับ Class

    Naming Conventions (แนวทางปฏิบัติ)

    ประเภทConventionตัวอย่าง
    Variables/FunctionscamelCaseuserName, getUserData
    ConstantsUPPER_SNAKE_CASEMAX_SIZE, API_URL
    Classes/ConstructorsPascalCaseUser, HttpClient
    Private (Convention)_prefix_internalMethod
    Booleanis/has/can/should prefixisActive, hasPermission