Middle
Kuidas töötab sulgumine (closure) JavaScriptis? Selgitage näite abil muutuja index ja funktsiooni run näitel teie lahenduses.
sobes.tech AI
Vastus AI-lt
In JavaScript, a closure is a function that remembers its lexical environment, even if it is called outside of its scope.
Let's look at an example with the variable index and the function run:
function createRunner() {
let index = 0;
function run() {
console.log(index);
index++;
}
return run;
}
const runner = createRunner();
runner(); // 0
runner(); // 1
runner(); // 2
Here, the run function closes over the variable index from the outer function createRunner. Even after createRunner has finished executing, run still has access to index and can modify its value. This allows maintaining state between calls to run.
Thus, closures enable creating functions with private variables and maintaining state without using global variables.