JavaScript ไม่มี Named Parameters (Keyword Arguments) ตรงๆ เช่น Python แต่เลียนแบบได้ด้วย Object Destructuring ในพารามิเตอร์ ส่งอ็อบเจกต์เข้ามา แล้ว destructuring ดึงค่าตามชื่อ — ทำให้เรียกฟังก์ชันอ่านง่าย ไม่ต้องจำลำดับพารามิเตอร์ และข้ามค่าเริ่มต้นได้
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Named Arguments</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.sample, .result { font-size: 18px; font-weight: 500; color: red; }
.result { color: rebeccapurple; }
</style>
</head>
<body>
<h1>Named Arguments ใน JavaScript Functions</h1>
<div class="sample"></div>
<div class="result"></div>
<button class="Btn">คลิกที่นี่</button>
<h3>กดปุ่มเพื่อเรียกฟังก์ชันพร้อมส่งอ็อบเจกต์เป็น Named Arguments</h3>
<script>
const sampleEle = document.querySelector(".sample");
const resultEle = document.querySelector(".result");
sampleEle.textContent = "{ a: 22, b: 44, c: 55, d: 99 }";
// Destructuring พร้อมค่าเริ่มต้น
function add({ a = 0, b = 0, c = 0, d = 0 }) {
return a + b + c + d;
}
document.querySelector(".Btn").addEventListener("click", () => {
resultEle.textContent = "ผลรวม = " + add({ a: 22, b: 44, c: 55, d: 99 });
});
</script>
</body>
</html>
ผลลัพธ์

เมื่อกดปุ่ม "คลิกที่นี่":

รูปแบบ Named Arguments ต่างๆ
// 1. Basic destructuring + defaults
function config({ host = "localhost", port = 3000, debug = false } = {}) {
return { host, port, debug };
}
config({ port: 8080 }); // { host: "localhost", port: 8080, debug: false }
config({}); // ค่าเริ่มต้นทั้งหมด
config(); // ต้องมี = {} ไม่งั้น error
// 2. Rename variables
function connect({ host: serverHost, port: serverPort }) { ... }
connect({ host: "db", port: 5432 });
// 3. Required parameters (บังคับส่ง)
function required({ mandatoryField }) {
if (mandatoryField === undefined) throw new Error("mandatoryField required");
}
// 4. Rest properties (เก็บส่วนที่เหลือ)
function process({ id, name, ...options }) {
console.log("Options:", options);
}
process({ id: 1, name: "test", timeout: 5000, retry: 3 });
// options = { timeout: 5000, retry: 3 }
ข้อดีและข้อจำกัด
| ข้อดี | ข้อจำกัด |
|---|---|
| อ่านโค้ดเรียกฟังก์ชันเข้าใจง่าย | Verbose สำหรับฟังก์ชันเล็ก (1-2 พารามิเตอร์) |
| ส่งเฉพาะที่ต้องการ ข้ามค่า default ได้ | ต้อง wrap ด้วย {} ทุกครั้ง | ลำดับพารามิเตอร์ไม่สำคัญ | ไม่รองรับ positional arguments ผสม | เพิ่มพารามิเตอร์ใหม่ไม่ breaking change | TypeScript ต้อง define interface/type | รองรับ default values ได้โดยตรง | Overhead เล็กน้อย (สร้าง object) |
Pattern: Options Object (Classic)
// ก่อน ES6 ใช้ options object ธรรมดา
function ajax(url, options) {
options = options || {};
const method = options.method || "GET";
const headers = options.headers || {};
// ...
}
ajax("/api", { method: "POST", headers: { "Content-Type": "application/json" } });
Destructuring ทำให้ pattern นี้สะดวกและอ่านง่ายขึ้นมาก