Khái niệm
JavaScript không có named parameters gốc, nhưng dùng Object Destructuring trong tham số hàm để mô phỏng. Cho phép: thứ tự tùy ý, bỏ qua tham số, giá trị mặc định, self-documenting.
Cú pháp
function myFunc({ param1 = default1, param2 = default2 } = {}) {
// param1, param2 có sẵn
}
// Gọi
myFunc({ param2: 'value', param1: 'other' }); // Thứ tự bất kỳ
Ví dụ hoàn chỉnh
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Named Parameters</title>
<style>
body { font-family: 'Segoe UI', sans-serif; padding: 20px; }
.sample, .result { font-size: 16px; font-weight: 500; margin: 10px 0; padding: 15px; border-radius: 4px; }
.sample { color: #d32f2f; background: #ffebee; }
.result { color: #6a1b9a; background: #f3e5f5; }
button { padding: 10px 20px; background: #1976d2; color: white; border: none; border-radius: 4px; cursor: pointer; }
</style>
</head>
<body>
<h1>Named Arguments trong JavaScript</h1>
<div class="sample" id="sample"></div>
<div class="result" id="result"></div>
<button id="btn">GỌI HÀM VỚI NAMED ARGS</button>
<h3>Nhấn nút để gọi hàm và truyền object làm tham số</h3>
<script>
const sampleEle = document.getElementById('sample');
const resultEle = document.getElementById('result');
const btn = document.getElementById('btn');
sampleEle.textContent = '{a: 22, b: 44, c: 55, d: 99}';
// Destructuring trong parameter với default values
function add({ a = 0, b = 0, c = 0, d = 0 } = {}) {
return a + b + c + d;
}
btn.addEventListener('click', () => {
const sum = add({ a: 22, b: 44, c: 55, d: 99 });
resultEle.textContent = `Tổng = ${sum}`;
// Demo thêm: gọi thiếu tham số
resultEle.textContent += `\nThiếu c,d: ${add({ a: 10, b: 20 })}`; // 30
resultEle.textContent += `\nThứ tự đảo: ${add({ d: 5, a: 1, c: 3, b: 2 })}`; // 11
resultEle.textContent += `\nRỗng: ${add({})}`; // 0
});
</script>
</body>
</html>
Kết quả
Tổng = 220 Thiếu c,d: 30 Thứ tự đảo: 11 Rỗng: 0
Ưu điểm
- ✅ Thứ tự tham số không quan trọng
- ✅ Self-documenting:
createUser({ name: 'A', age: 20 }) - ✅ Bỏ qua tham số tùy ý (dùng default)
- ✅ Dễ mở rộng thêm tham số mới không breaking change
- ✅ Dễ đọc khi nhiều tham số (>3)
So sánh
// ❌ Positional - khó nhớ thứ tự
createUser('John', 25, 'john@mail.com', true, 'admin');
// ✅ Named - rõ ràng
createUser({
name: 'John',
age: 25,
email: 'john@mail.com',
isActive: true,
role: 'admin'
});
Pattern phổ biến: Options Object
function fetchData(url, options = {}) {
const {
method = 'GET',
headers = {},
body = null,
timeout = 5000,
retries = 3,
onProgress = () => {}
} = options;
// Implementation...
}
// Gọi
fetchData('/api/users', {
method: 'POST',
body: JSON.stringify({ name: 'Test' }),
timeout: 10000
});
Kết hợp với TypeScript
interface FetchOptions {
method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
headers?: Record;
body?: any;
timeout?: number;
}
function fetchData(url: string, options: FetchOptions = {}) {
const { method = 'GET', ... } = options;
// TypeScript check types
}
Lưu ý
- Object destructuring parameter không thể bỏ qua hoàn toàn nếu không có
= {}default add({ a: 1 })OK,add()lỗi nếu không có= {}- Performance: Tạo object mới mỗi lần gọi (thường không đáng lo)