闭包(Closure)是指当一个函数“记住”其词法作用域时,即使该函数在该词法作用域之外执行。这是 JavaScript 中数据隐私的秘密。
背包比喻
想象一个函数是一个徒步旅行者。
当徒步旅行者离家(外部函数)时,他们打包一个 背包(闭包)。
他们把家里需要的所有变量放进背包里。
即使房子被烧毁(外部函数结束),徒步旅行者仍然拥有他们的背包,变量在里面是安全的。
"银行账户" 模式
在许多语言中,你有 private 变量。在 JS 中,我们使用闭包。 这是一个经典的 高级开发人员面试问题。
javascript
function createBankAccount(initialBalance) {
// 这个变量是私有的。
// 没有人可以从外部直接访问它。
let balance = initialBalance;
return {
deposit: (amount) => {
balance += amount;
return `已存入 ${amount}。新余额:${balance}`;
},
withdraw: (amount) => {
if (amount > balance) return "资金不足";
balance -= amount;
return `已提取 ${amount}。新余额:${balance}`;
},
// 我们不返回 'balance' 变量,所以它保持隐藏。
getBalance: () => balance
};
}
const myAccount = createBankAccount(100);
console.log(myAccount.deposit(50)); // 150
console.log(myAccount.balance); // undefined (摸不到它!)
console.log(myAccount.getBalance()); // 150 (必须礼貌地询问)为什么这很专业?
如果 balance 是一个全局变量,你的代码的任何部分都可能意外地将其设置为 0。通过使用闭包,你保证余额只能使用你创建的 deposit 和 withdraw 规则进行更改。