JS không có private field native (trước ES2022 #privateField). Dùng **IIFE (Immediately Invoked Function Expression)** tạo scope private.
Vấn đề: Pollute global namespace
const HIDDEN_CONST = 100;
function fnWeWantToHide(x, y) { return (x + y) * HIDDEN_CONST; }
console.log(fnWeWantToHide(1, 2)); // 300 — HIDDEN_CONST, fnWeWantToHide leak ra global
Giải pháp: IIFE
(() => {
const HIDDEN_CONST = 100;
function fnWeWantToHide(x, y) { return (x + y) * HIDDEN_CONST; }
console.log(fnWeWantToHide(1, 2)); // 300
})();
// HIDDEN_CONST, fnWeWantToHide KHÔNG tồn tại ở global scope
Module Pattern (IIFE trả về public API)
const MyModule = (() => {
let privateCount = 0;
const increment = () => ++privateCount;
const getCount = () => privateCount;
return { increment, getCount }; // public API
})();
MyModule.increment();
console.log(MyModule.getCount()); // 1
// privateCount không truy cập được từ bên ngoài
Modern: ES2022 Private Fields
class MyClass {
#privateField = 0;
#privateMethod() { return this.#privateField; }
publicMethod() { return this.#privateMethod(); }
}
Kết luận: IIFE/Module pattern = encapsulation trước ES2022. Nay dùng #field native.