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

Triển khai Private Property bằng Closure trong JavaScript


Closure cho phép hàm con truy cập biến của hàm cha sau khi hàm cha đã return. Dùng để tạo private state (biến a không truy cập trực tiếp từ bên ngoài).

Ví dụ

Counter với private variable a:

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Private property closure</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 20px; font-weight: 500; color: blueviolet; }
  </style>
</head>
<body>
  <h1>Private Property bằng Closure trong JavaScript</h1>
  <div class="result">0</div>
  <br />
  <button class="Btn">TĂNG GIÁ TRỊ</button>
  <h3>Nhấn nút để tăng counter (biến a private trong closure)</h3>
  <script>
    const btn = document.querySelector('.Btn');
    const resEle = document.querySelector('.result');
    function createCounter() {
      let a = 0; // Private variable
      return function increment() {
        a++;
        return a;
      };
    }
    const counter = createCounter();
    btn.addEventListener('click', () => {
      resEle.textContent = counter();
    });
  </script>
</body>
</html>

Kết quả

Mỗi click tăng: 1, 2, 3... Biến a không thể truy cập từ bên ngoài.

ES2022: Dùng #privateField trong class cho private property thật sự.