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

Invoke Function as Function และ Method ใน JavaScript

Function เรียกได้ 2 แบบ: Function Invocation (this = global/undefined) และ Method Invocation (this = Object Owner)

ตัวอย่าง

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Function vs Method Invocation</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 20px; font-weight: 500; }
  </style>
</head>
<body>
  <h1>Invoke Function as Function and Method</h1>
  <div style="color: green;" class="result"></div>
  <button class="Btn">CLICK HERE</button>
  <h3> Click to invoke as function and method </h3>
  <script>
    let resEle = document.querySelector(".result");
    function add(a, b) { return a + b; }
    let obj = {
      firstName: 'Rohan',
      lastName: 'Sharma',
      welcome() { return 'Welcome ' + this.firstName + ' ' + this.lastName; }
    };
    document.querySelector(".Btn").addEventListener("click", () => {
      resEle.innerHTML = 'Function: add(2,3) = ' + add(2,3) + '<br>';
      resEle.innerHTML += 'Method: obj.welcome() = ' + obj.welcome() + '<br>';
    });
  </script>
</body>
</html>

คำอธิบาย

Function Invocation

  • add(2, 3) - เรียกเป็น Function ธรรมดา
  • this = Global (Window) หรือ undefined (Strict Mode)

Method Invocation

  • obj.welcome() - เรียกผ่าน Object
  • this = obj (Owner Object)

Constructor Invocation

  • new Add() - this = Instance ใหม่

Indirect Invocation (call/apply/bind)

  • add.call(obj, 2, 3) - กำหนด this เอง

ผลลัพธ์

Function: add(2,3) = 5
Method: obj.welcome() = Welcome Rohan Sharma