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

วิธีเรียกใช้ JavaScript Function เป็นฟังก์ชันทั่วไป

การเรียกใช้ JavaScript Function เป็นฟังก์ชันทั่วไป (Function Invocation) คือการเรียกโดยตรงด้วยชื่อฟังก์ชันตามด้วยวงเล็บ ()

ตัวอย่าง

<html>
  <head>
    <script>
      function Display() {
        document.write("Hello World!");
      }
    </script>
  </head>
  <body>
    <p>คลิกปุ่มด้านล่างเพื่อเรียกใช้ฟังก์ชัน</p>
    <form>
      <input type="button" onclick="Display()" value="Display">
    </form>
  </body>
</html>

รูปแบบการเรียกใช้ฟังก์ชัน (Invocation Patterns)

ตัวอย่างเพิ่มเติม

// 1. Function Declaration
function greet(name) {
  return "Hello " + name;
}
greet("John"); // Function Invocation

// 2. Function Expression
const add = function(a, b) { return a + b; };
add(1, 2); // Function Invocation

// 3. Arrow Function
const multiply = (a, b) => a * b;
multiply(3, 4); // Function Invocation

// 4. IIFE (Immediately Invoked)
(function() {
  console.log("Runs immediately");
})();

// 5. Callback
setTimeout(function() {
  console.log("Later");
}, 1000);

Function Invocation ภายใน Method (ปัญหา this)

const obj = {
  value: 10,
  method: function() {
    function inner() {
      console.log(this.value); // undefined (strict) หรือ window.value
    }
    inner(); // Function Invocation - this หายไป!
  }
};

obj.method();

// แก้ด้วย Arrow Function
const obj2 = {
  value: 10,
  method: function() {
    const inner = () => console.log(this.value); // Lexical this
    inner();
  }
};
obj2.method(); // 10

สรุป: เรียกฟังก์ชันทั่วไปด้วย func() เรียก Method ด้วย obj.method() เรียก Constructor ด้วย new Func()

PatternSyntaxthis Binding
Function Invocationfunc()Global (window) / undefined (strict)
Method Invocationobj.method()Object (obj)
Constructor Invocationnew Func()Instance ใหม่
Call/Apply/Bindfunc.call(thisArg, ...)ตามที่ระบุ (thisArg)