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

วิธีใช้ Function Literal กำหนดฟังก์ชันใน JavaScript

JavaScript 1.2 นำเสนอ concept ของ function literals ซึ่งเป็นวิธีใหม่ในการกำหนดฟังก์ชัน Function literal คือ expression ที่กำหนด unnamed function (anonymous function)

ตัวอย่าง

<html> 
  <head> 
    <script> 
      <!-- 
        var func = function(x, y) { return x * y }; 
        function secondFunction() { 
          var result; 
          result = func(10, 20); 
          document.write(result); 
        } 
      //--> 
    </script> 
  </head> 
  <body> 
    <p>Click the following button to call the function</p> 
    <form> 
      <input type="button" onclick="secondFunction()" value="Call Function"> 
    </form> 
    <p>Use different parameters inside the function and then try...</p> 
  </body> 
</html>

Function Literal = Function Expression

// Named function expression
var factorial = function fact(n) {
  return n <= 1 ? 1 : n * fact(n - 1);  // เรียกตัวเองได้ด้วยชื่อ fact
};

// Anonymous function expression (arrow function ES6+)
const multiply = (x, y) => x * y;

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

Function Declaration vs Function Expression

ลักษณะFunction DeclarationFunction Expression
Syntaxfunction name() {}var name = function() {}
Hoistingทั้งฟังก์ชันแค่ตัวแปร (var)
Nameบังคับต้องมีอาจไม่มี (anonymous)
ScopeFunction-scopedขึ้นอยู่กับ var/let/const

สมัยใหม่: ใช้ const + arrow function หรือ function expression แทน var