JavaScript Closures: Hiểu đúng và sử dụng hiệu quả
Trang chủBlogChi tiết
JavaScriptFundamentals

JavaScript Closures: Hiểu đúng và sử dụng hiệu quả

18/12/2024
5 phút đọc
Quay lại danh sách

JavaScript Closures: Hiểu đúng và sử dụng hiệu quả

Closure là gì?

Closure là một function có thể "nhớ" và truy cập được lexical scope của nó, ngay cả khi function đó được thực thi bên ngoài scope ban đầu.

1. Ví dụ cơ bản

function createCounter() {
  let count = 0;  // Private variable
  
  return function() {
    count++;
    return count;
  };
}

const counter = createCounter();
console.log(counter());  // 1
console.log(counter());  // 2
console.log(counter());  // 3

2. Use Cases thực tế

2.1. Private Variables (Encapsulation)

function BankAccount(initialBalance) {
  let balance = initialBalance;  // Private
  
  return {
    deposit: function(amount) {
      balance += amount;
      return balance;
    },
    withdraw: function(amount) {
      if (amount > balance) {
        throw new Error('Insufficient funds');
      }
      balance -= amount;
      return balance;
    },
    getBalance: function() {
      return balance;
    }
  };
}

const myAccount = BankAccount(1000);
myAccount.deposit(500);    // 1500
myAccount.withdraw(200);   // 1300
// myAccount.balance;      // undefined - không truy cập trực tiếp được!

3. Kết luận

Ưu điểm Closures:

  • Encapsulation (private variables)
  • Function factory pattern
  • Callback handlers với state

Nhược điểm:

  • Có thể gây memory leaks nếu không cẩn thận
  • Khó debug hơn
Chia sẻ bài viết: