閉包是一項功能,允許函數存取在相同作用域層級(詞法作用域)中聲明的所有其他變數和函數。
JavaScript 中的閉包與 Java 中的私有方法具有類似的用途,可讓您建立私有變數並封裝功能。
function outerFunction() { let outerVariable = 'I am from outer scope'; function innerFunction() { console.log(outerVariable); // Accessing outerVariable from the outer scope } return innerFunction; // Return the inner function } const closureFunction = outerFunction(); // Call outerFunction, which returns innerFunction closureFunction(); // Outputs: I am from outer scope
function handleCount() { let count = 0; return { increment: () => { count++; return count; }, decrement: () => { count--; return count; }, getCount: () => { return count; }, }; } const counter = handleCount(); console.log(counter.increment()); // Outputs: 1 console.log(counter.increment()); // Outputs: 2 console.log(counter.getCount()); // Outputs: 2 console.log(counter.decrement()); // Outputs: 1 console.log(counter.getCount()); // Outputs: 1
以上是掌握 JavaScript 中的閉包:了解範圍、封裝和效能的詳細內容。更多資訊請關注PHP中文網其他相關文章!