Please explain what a closure is and provide a simple real-world example of using a closure.
分类: technical
难度: easy
标签:
答题技巧
["Define closure: function + lexical environment it was created in","Key point: the function remembers and can access variables from its birthplace scope","Common uses: data privacy, state preservation, function factories, callbacks","Best to show code example (counter, debounce, throttle, module pattern etc.)","Be prepared for follow-up: memory leak risk, classic for-loop closure trap"]
参考答案
A closure is a function that remembers and can access variables from its lexical scope even when the function is executed outside that scope. Example (counter): ```javascript function createCounter() { let count = 0; return function() { return ++count; }; } const counter = createCounter(); console.log(counter()); // 1 console.log(counter()); // 2 ```