Closure is a feature in JavaScript that allows a function to access and use variables from its outer scope, including variables that have escaped the scope of the function. This means that variables can still be accessed even after the function has completed its execution.
Let's take a simple example of Closure in JavaScript:
function outerFunction() {
var message = 'Hello';
function innerFunction() {
console.log(message);
}
return innerFunction;
}
var myFunction = outerFunction();
myFunction(); // In ra: Hello
In the example above, we have an outerFunction that contains a variable called message and an innerFunction declared within outerFunction. The outerFunction returns the innerFunction.
When we call outerFunction and assign the return value to the variable myFunction, the message variable is still retained in memory, even though the outerFunction has completed its execution. Then, when we call the myFunction, it can still access and print the value of the message variable.
This is an example of Closure, where an innerFunction can access the variable message from its outer scope.
Closure allows us to create private variables by using functions. This means that variables can only be accessed and used within the scope of that function, and cannot be accessed from outside. This is a great way to hide information and protect data.
function createCounter() {
let count = 0;
return function() {
count++;
console.log(count);
};
}
const counter = createCounter();
counter(); // In ra: 1
counter(); // In ra: 2
In the example above, we have a function createCounter that creates a variable count and returns another function. The returned function can access and increment the value of count every time it is called. The count variable cannot be accessed directly from outside createCounter, but can only be used through the returned function.
Closure also allows us to create callback functions to handle events or asynchronous tasks. We can pass variables and parameters into the callback function and use them in the processing.
function fetchData(url, callback) {
// Khi dữ liệu đã được tải về
const data = 'Dữ liệu từ API';
// Gọi hàm gọi lại và truyền dữ liệu vào
callback(data);
}
function processResponse(response) {
console.log('Xử lý dữ liệu:', response);
}
fetchData('https://api.example.com', processResponse);
In the example above, we have a function called fetchData to load data from a URL. We also have a function called processResponse to handle the downloaded data. By using Closure, we can pass the processResponse function as a callback function and use the downloaded data in this function.
Closure provides us with the ability to create stateful variables. This means that variables retain their values after the function has completed its execution. This is useful for storing state or important information between function calls.
function createLogger() {
let logs = [];
return {
addLog: function(message) {
logs.push(message);
console.log('Log:', message);
},
getLogs: function() {
return logs;
}
};
}
const logger = createLogger();
logger.addLog('Bắt đầu quá trình xử lý');
logger.addLog('Hoàn thành quá trình xử lý');
console.log(logger.getLogs()); // In ra: ['Bắt đầu quá trình xử lý', 'Hoàn thành quá trình xử lý']
In the example above, we have a function createLogger that creates an array logs and returns an object with two methods. The addLog method is used to add a log to the logs array, while the getLogs method returns the logs array. By using Closure, each time the addLog function is called, the logs array is preserved and maintains its state between calls.