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

การเรียกใช้ฟังก์ชันด้วย call() และ apply() ใน JavaScript

call() และ apply() เป็น Methods ของ Function ใช้สำหรับเรียกฟังก์ชันพร้อมกำหนด this Context และส่ง Arguments ความแตกต่างคือรูปแบบการส่ง Arguments

ตัวอย่างโค้ด

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>call & apply</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 18px; font-weight: 500; color: blueviolet; }
  </style>
</head>
<body>
  <h1>เรียกใช้ฟังก์ชันด้วย call() และ apply()</h1>
  <div class="result"></div>
  <br />
  <button class="Btn">คลิกที่นี่</button>
  <h3>คลิกปุ่มด้านบนเพื่อเรียกฟังก์ชันด้วย call() และ apply()</h3>
  <script>
    const resEle = document.querySelector(".result");
    const BtnEle = document.querySelector(".Btn");
    
    function addNum(num1, num2, num3, num4) {
      return num1 + num2 + num3 + num4;
    }
    
    function multiplyNum(num1, num2, num3, num4) {
      return num1 * num2 * num3 * num4;
    }
    
    const arr = [22, 33, 44, 55];
    
    BtnEle.addEventListener("click", () => {
      // call: ส่ง Arguments แบบรายตัว
      const sum = addNum.call(this, 22, 33, 44, 55);
      
      // apply: ส่ง Arguments เป็น Array
      const product = multiplyNum.apply(this, arr);
      
      resEle.innerHTML = `Sum = ${sum}<br>`;
      resEle.innerHTML += `Product = ${product}<br>`;
    });
  </script>
</body>
</html>

ความแตกต่าง call vs apply vs bind

MethodArgumentsInvoke ทันที?Return
call(this, a, b, c)รายตัว (Comma separated)✅ ใช่Function Result
apply(this, [a, b, c])Array/Array-like✅ ใช่Function Result
bind(this, a, b)รายตัว (Partial OK)❌ ไม่ (คืน Function ใหม่)Bound Function

Use Cases


// 1. Borrow Method จาก Object อื่น
const obj = { name: "John" };
function greet(greeting, punctuation) {
  return `${greeting}, ${this.name}${punctuation}`;
}
greet.call(obj, "Hello", "!");     // "Hello, John!"
greet.apply(obj, ["Hi", "?"]);     // "Hi, John?"

// 2. Array-like to Array (Arguments, NodeList)
function sum() {
  return [...arguments].reduce((a, b) => a + b, 0);
}
sum.call(null, 1, 2, 3); // 6

// 3. Math Functions กับ Array
const numbers = [5, 10, 15, 20];
Math.max.apply(null, numbers);  // 20
Math.max(...numbers);           // 20 (Spread - Modern)

// 4. Constructor Borrowing
function Animal(name) { this.name = name; }
function Dog(name, breed) {
  Animal.call(this, name); // เรียก Parent Constructor
  this.breed = breed;
}

ผลลัพธ์

Sum = 154, Product = 17556000