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

วิธีตั้งชื่อ JavaScript Identifiers ให้ถูกต้อง

JavaScript Identifiers คือ ชื่อสำหรับ Variables, Functions, Classes, Properties ฯลฯ ต้องปฏิบัติตามกฎดังนี้:

กฎข้อห้าม (Must Not)

  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 และ Future Reserved Words: enum, implements, interface, package, private, protected, public, static
  2. ห้ามขึ้นต้นด้วยตัวเลข (0-9): 5demo ❌ → _5demo ✅ หรือ demo5 ✅

กฎที่อนุญาต (Allowed)

  • ตัวอักษร (a-z, A-Z, Unicode Letters)
  • ตัวเลข (0-9) ไม่ใช่ตัวแรก
  • Underscore (_)
  • Dollar Sign ($)

Case Sensitivity

JavaScript Case-Sensitive: Name ≠ name ≠ NAME

ตัวอย่าง Valid/Invalid

IdentifierValid?เหตุผล
userName✅CamelCase ปกติ
_private✅ขึ้นต้น _ ได้
$element✅ขึ้นต้น $ ได้
var❌Reserved Keyword
123abc❌ขึ้นต้นตัวเลข
my-var❌Hyphen ไม่ได้ (ใช้ myVar)
ชื่อตัวแปร✅Unicode OK แต่ไม่แนะนำ

Naming Conventions (แนวทางมาตรฐาน)

ประเภทStyleตัวอย่าง
Variables/FunctionscamelCaseuserName, getUserData
ConstantsUPPER_SNAKE_CASEMAX_SIZE, API_ENDPOINT
Classes/ConstructorsPascalCaseUser, HttpClient
Private (Convention)_prefix_internalHelper
Booleanis/has/can/shouldisActive, hasAccess