> For the complete documentation index, see [llms.txt](https://lifeoverflow.gitbook.io/learning-javascript/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lifeoverflow.gitbook.io/learning-javascript/javascript-es5-jiao-xue/closure.md).

# Closure

**其他語言也有closure**

**可提供類似其他語言的static function-使用static data, 以及跟module pattern結合提供內部private function的空間**

**Closure使用到的變數的lifetime**只要還有人指到這個closure function時，這些變數就會隨著存活.

<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures> *A closure is a function having access to the parent scope, even after the parent function has closed.*

上述link有提到跟 closure相關的 **lexical scoping**:

*the code and see that this works. This is an example of lexical scoping: in JavaScript, the scope of a variable is defined by its location within the source code (it is apparent lexically) and nested functions have access to variables declared in their outer scope.*

上述link裡的example, 放在online JB Bin上:<http://jsbin.com/wurihum/edit?html,js,output> 其code:

```javascript
var add = (function () {
  var counter = 0;
  debugger;  
  return function () {
    counter = counter +1;
    debugger; //用chrome dev tool看, 會看到closure scope
    return counter;  
  };
})();

add();
debugger;
add();
debugger;
add();
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://lifeoverflow.gitbook.io/learning-javascript/javascript-es5-jiao-xue/closure.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
