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

Function Literal ใน JavaScript คืออะไร

Function Literal คือนิพจน์ที่นิยามฟังก์ชันโดยไม่มีชื่อ (unnamed function) หรือที่เรียกว่า Anonymous Function ลองรันโค้ดด้านล่างเพื่อดูการใช้งาน Function Literal ใน JavaScript:

ตัวอย่าง

<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>
  </body>
</html>

คำอธิบาย: var func = function(x,y){ return x*y }; คือ Function Expression (Function Literal) กำหนดฟังก์ชันไว้ในตัวแปร func ต่างจาก Function Declaration function func(x,y){...} ที่มี Hoisting Function Literal ใช้ได้เป็น First-class citizen: ส่งเป็นอาร์กิวเมนต์, คืนค่า, เก็บในตัวแปร, ใส่ในอาร์เรย์/ออบเจ็กต์