Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Sử dụng Function Literal để định nghĩa Function trong JavaScript


JavaScript 1.2 giới thiệu function literals - cách mới định nghĩa function. Function literal là expression định nghĩa function không tên (anonymous).

Ví dụ

<html>
  <head>
    <script>
      // Function literal gán cho biến
      var func = function(x, y) { return x * y; };
      
      function secondFunction() {
        var result;
        result = func(10, 20); // Gọi function qua biến
        document.write(result); // 200
      }
    </script>
  </head>
  <body>
    <p>Click nút để gọi function</p>
    <form>
      <input type="button" onclick="secondFunction()" value="Call Function">
    </form>
    <p>Thử tham số khác nhau...</p>
  </body>
</html>

Function Literal vs Function Declaration

Đặc điểmFunction Literal (Expression)Function Declaration
Cú phápvar f = function() {}function f() {}
TênAnonymous (hoặc named function expression)Bắt buộc có tên
HoistingChỉ biến (var/let/const)Toàn bộ function
Có thể gọi trước định nghĩa?KhôngCó
Dùng làm giá trị (argument, return)Có (first-class citizen)Không trực tiếp
Arrow functionES6 syntactic sugar cho function expressionKhông áp dụng

Named Function Expression (NFE)

var factorial = function fact(n) {
  return n <= 1 ? 1 : n * fact(n - 1); // Đệ quy dùng tên nội bộ 'fact'
};

console.log(factorial.name); // "fact" - debug stack trace đẹp

Function Expression trong Modern JS

  • const/let + arrow function: const add = (a, b) => a + b;
  • const + function expression: const handleClick = function(e) { ... };
  • Callback, higher-order functions: arr.map(x => x * 2).
  • IIFE: (() => { ... })().

Khi nào dùng Function Declaration?

  • Function độc lập, reusable, cần hoisting.
  • Method trong class/object (method shorthand).
  • Recursive function (dễ đọc hơn NFE).

Kết luận

Function literal = function expression = first-class function. Là nền tảng của functional programming trong JS. ES6 arrow function là cú pháp ngắn gọn hơn cho function expression.