JavaScript Closures: MDN docs
Closures are a fundamental concept in JavaScript, enabling the code to maintain access to an outer function's scope, even after the outer function has finished execution. They are one of JavaScript's most powerful features, commonly used in functional programming and indispensable for event handlers and modules.
This guide explores closures in JavaScript, providing an in-depth understanding through practical examples, as per the Mozilla Developer Network (MDN) documentation.
Understanding Closures
Closures allow a function to have access to its own scope, the outer function's scope, and the global scope. To grasp this, let's start with a simple example:
A closure forms whenever a function is created, at function creation time.
Function Creation
In the following snippet, two scopes are created: the global scope (window in browsers) and the local scope within the 'makeCounter' function.
function makeCounter() {
let count = 0;
return function() { // This inner function has access to 'count'
return count++;
};
}
Using the Counter
Now,每次调用`makeCounter()`时,都会返回一个新的闭包,每个闭包都会记录自己的计数:
const counter1 = makeCounter();
const counter2 = makeCounter();
console.log(counter1()); // 0, counter2 does not influence counter1's count
console.log(counter1()); // 1, still incrementing its own count
console.log(counter2()); // 0, each closed scope is independent
Closures in Loops
Closures often come into play when working with loops. Without closures, inner functions would not be able to pull the correct value from the array to execute the respective handler:
Without Closures
Suppose we need to create a set of buttons with specific IDs and corresponding click event handlers:
for (let i = 0; i < 5; i++) {
const btn = document.createElement('button');
btn.innerText = `Button ${i + 1}`;
btn.addEventListener('click', function () {
console.log('Button', i + 1, 'was clicked.'); // Always logs 6 regardless of clicked button
});
document.body.appendChild(btn);
}
With Closures
To achieve the desired result, wrap the event listener with an immediate invoked function expression (IIFE):
for (let j = 0; j < 5; j++) {
const btn = document.createElement('button');
btn.innerText = `Button ${j + 1}`;
btn.addEventListener('click', ((k) => () => {
console.log('Button', k, 'was clicked.');
})(j + 1));
document.body.appendChild(btn);
}
Each button click will now log the correct button number due to closures preserving the variable's value at the time of the IIFE's creation.
Mastering closures is crucial for writing efficient and scalable JavaScript code. Now that you're familiar with this concept, you can delve into more advanced topics like currying, partial application, and Dean Edward's Immediate Functions Invoked for Proper Scoping (IIFE).
Happy coding!