Home > Article > Web Front-end > Common closure application cases in programming
Common application scenarios of closures in programming require specific code examples
In programming, closure (Closure) is a powerful and common concept. It means that a function can access and manipulate variables within the lexical scope at the time of its definition. Closures can play a role in many scenarios. The following will introduce several common application scenarios and provide specific code examples.
function createCounter() { let count = 0; return function() { count++; console.log(count); } } const counter = createCounter(); counter(); // 输出 1 counter(); // 输出 2
In this example, the createCounter
function returns an internal function that can access and modify the count
variable. The count
variable cannot be accessed directly from the outside, and the value of count
can only be incremented and output by calling the counter
function.
function debounce(callback, delay) { let timerId = null; return function() { if (timerId) { clearTimeout(timerId); } timerId = setTimeout(callback, delay); } } function inputChange() { console.log('Input changed.'); } const inputElement = document.getElementById('input'); inputElement.addEventListener('input', debounce(inputChange, 500));
In this example, the debounce
function returns a closure, which defines a timerId internally.
Variables. When the input
event is triggered, the function inside the closure will first clear the previous timer, and then set a new timer to ensure that the callback function is executed after delay
milliseconds.
function fetchData(url) { return new Promise(function(resolve, reject) { fetch(url).then(function(response) { resolve(response); }).catch(function(error) { reject(error); }); }); } function handleResponse(response) { console.log(response); } fetchData('https://api.example.com/data').then(handleResponse);
In this example, the fetchData
function returns a Promise and defines a closure inside it. In the callback function inside the closure, you can access the context of the external function, including the resolve
and reject
functions.
Closure is a powerful and common programming concept that is often used to implement private variables, anti-shake throttling functions, and save the state of the context. The above are common application scenarios of closures in programming, and specific code examples are provided. By deeply understanding the principles and application scenarios of closure, we can better use it to solve practical problems.
The above is the detailed content of Common closure application cases in programming. For more information, please follow other related articles on the PHP Chinese website!