- Регистрация
- 1 Мар 2015
- Сообщения
- 1,481
- Баллы
- 155
Closures in JavaScript occur when a function retains access to variables from its lexical scope, even after the outer function has finished execution. This allows functions to "remember" values and maintain state.
? Simple Example:
function outerFunction() {
let counter = 0; // Local variable
return function innerFunction() {
counter++; // Inner function remembers 'counter'
console.log(counter);
};
}
const increment = outerFunction(); // Returns innerFunction
increment(); // 1
increment(); // 2
increment(); // 3
? Explanation:
Closures are useful for encapsulation, maintaining private variables, and creating efficient event handlers. ?
? Simple Example:
function outerFunction() {
let counter = 0; // Local variable
return function innerFunction() {
counter++; // Inner function remembers 'counter'
console.log(counter);
};
}
const increment = outerFunction(); // Returns innerFunction
increment(); // 1
increment(); // 2
increment(); // 3
? Explanation:
- outerFunction() defines a local variable (counter).
- innerFunction() modifies counter, but the outer function has already executed!
- However, innerFunction() retains access to counter due to closure behavior.
- Each call to increment() updates the retained counter, demonstrating persistent state.
Closures are useful for encapsulation, maintaining private variables, and creating efficient event handlers. ?