Closure is a feature that allows the functions to access all other variables and functions which are declared in same scope level (lexical scope).
Closures in JavaScript serve a similar purpose to private methods in Java by allowing you to create private variables and encapsulate functionality.
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
The above is the detailed content of Mastering Closures in JavaScript: Understanding Scope, Encapsulation, and Performance. For more information, please follow other related articles on the PHP Chinese website!