Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Truyền tham số cho callback function trong JavaScript


Callback function là hàm truyền vào hàm khác. Để truyền tham số cho callback, dùng closure (arrow function bọc) hoặc bind. Ví dụ: fn(() => callback(arg)).

Ví dụ

Hàm multiply9(fn, num) gọi fn(num) rồi nhân 9. Truyền add2 làm callback:

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Callback với tham số</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>Truyền tham số cho callback function</h1>
  <div class="result"></div>
  <button class="Btn">THỰC HIỆN</button>
  <h3>Nhấn để gọi multiply9(add2, 8) -> (8+2)*9 = 90</h3>
  <script>
    const resEle = document.querySelector(".result");
    function add2(a) { return a + 2; }
    function multiply9(fn, num) { return fn(num) * 9; }
    document.querySelector(".Btn").addEventListener("click", () => {
      resEle.textContent = `Kết quả = ${multiply9(add2, 8)}`; // 90
    });
  </script>
</body>
</html>

Kết quả

Kết quả = 90 ( (8+2) * 9 ).

Mở rộng: Nếu callback cần nhiều tham số cố định: multiply9((x) => add2(x, extra), 8) hoặc dùng add2.bind(null, extra).