Callback Function คือฟังก์ชันที่ส่งผ่านอีกฟังก์ชันหนึ่ง (Higher-Order Function) เพื่อเรียกใช้ภายหลัง การส่งพารามิเตอร์ให้ Callback ทำได้ 2 วิธีหลัก: 1) Closure (ฟังก์ชันภายในเข้าถึงตัวแปรภายนอก) 2) Partial Application / Bind (สร้างฟังก์ชันใหม่ผูกพารามิเตอร์ไว้ล่วงหน้า)
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Callback Parameters</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 20px; font-weight: 500; color: blueviolet; }
</style>
</head>
<body>
<h1>ส่งพารามิเตอร์ให้ Callback Functions</h1>
<div class="result"></div>
<button class="Btn">คลิกที่นี่</button>
<h3>กดปุ่มเพื่อส่งพารามิเตอร์ให้ Callback add2 แล้วเรียกใน multiply9</h3>
<script>
const resEle = document.querySelector(".result");
// Callback function
function add2(a) {
return a + 2;
}
// Higher-order function: รับ callback fn และ parameter num
function multiply9(fn, num) {
return fn(num) * 9;
}
document.querySelector(".Btn").addEventListener("click", () => {
const result = multiply9(add2, 8); // add2(8) = 10, 10 * 9 = 90
resEle.textContent = "ผลลัพธ์ = " + result;
});
</script>
</body>
</html>
ผลลัพธ์

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

เทคนิคการส่งพารามิเตอร์ให้ Callback
1. Closure (Factory Function) — แนะนำ
function createMultiplier(factor) {
// คืนฟังก์ชันใหม่ที่ "จดจำ" factor
return (number) => number * factor;
}
const double = createMultiplier(2);
const triple = createMultiplier(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15
// ใช้กับ Array Methods
const numbers = [1, 2, 3];
const multiplyBy = (factor) => (num) => num * factor;
numbers.map(multiplyBy(10)); // [10, 20, 30]
2. Function.bind() — ผูก this และ Arguments
function greet(greeting, name) {
return `${greeting}, ${name}!`;
}
const sayHello = greet.bind(null, "Hello"); // ผูก argument แรก
console.log(sayHello("World")); // "Hello, World!"
// ใช้กับ Event Handlers
class Button {
constructor(label) {
this.label = label;
this.element = document.createElement("button");
this.element.textContent = label;
// ผูก this และ argument
this.element.addEventListener("click", this.handleClick.bind(this, "clicked"));
}
handleClick(action, event) {
console.log(`${this.label} ${action}`);
}
}
3. Arrow Function Wrapper (Inline)
// ส่ง callback พร้อม argument inline
button.addEventListener("click", () => myCallback(arg1, arg2, event));
// หรือ wrapper function
const withArgs = (fn, ...fixedArgs) => (...restArgs) => fn(...fixedArgs, ...restArgs);
const handler = withArgs(log, "USER_ACTION", { timestamp: Date.now() });
element.addEventListener("click", handler);
4. Partial Application Helper
const partial = (fn, ...presetArgs) => (...laterArgs) => fn(...presetArgs, ...laterArgs);
const add = (a, b, c) => a + b + c;
const add10 = partial(add, 10); // a=10
const add10_20 = partial(add, 10, 20); // a=10, b=20
console.log(add10(5)); // 25 (10+5+10? wait - let's fix)
console.log(add10_20(30)); // 60 (10+20+30)
ใช้กับ Array Methods (Map/Filter/Reduce)
const users = [
{ id: 1, name: "Alice", role: "admin" },
{ id: 2, name: "Bob", role: "user" },
];
// ❌ ไม่ส่ง argument ให้ callback ได้โดยตรง
// users.filter(user => user.role === "admin"); // hardcoded
// ✅ Factory Function
const byRole = (role) => (user) => user.role === role;
const admins = users.filter(byRole("admin"));
// ✅ Bind (less common for this)
const hasRole = (role, user) => user.role === role;
const admins2 = users.filter(hasRole.bind(null, "admin"));
สรุป
| วิธี | ใช้เมื่อ | ข้อดี |
|---|---|---|
| Closure / Factory | สร้าง callback หลายรูปแบบจาก template เดียว | อ่านง่าย, Flexible, Functional Style |
| bind() | ต้องการผูก this + arguments | Built-in, รองรับ this context |
| Arrow Wrapper | Inline, ครั้งเดียว, สั้น | เรียบง่าย ไม่ต้องสร้างฟังก์ชันเพิ่ม |
| Partial Helper | Reusable utility, Point-free style | Composable, Declarative |