每次提到closure首先想到的都是「Friends」里Rachel喝高了给Ross留语音的这个场景.. 🙂

好了当然我说的不是这个。
Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure ‘remembers’ the environment in which it was created.
A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains:
- it has access to its own scope (variables defined between its curly brackets)
- it has access to the outer function’s variables
- it has access to the global variables.
The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly.
最典型的一个例子是点第i个node就alert i的那个。

注意啦上面这个当然是错误代码!因为我们说inner function has access to the variables of the outer functions,指的是the actual variables,而不是copies of them。上面的代码最后alert的是有多少个node。
正确代码:

在for循环外面定义一个helper function,这个helper function的作用就是deliver a function that binds the current value of i.
一开始老是闹不明白。后来看到一句话: Avoid creating functions within a loop. 真是在培养best practice的同时避免了上面的那种错误。
另外一个跟DOM有关的例子(我最喜欢DOM了呵呵):
Define a function that sets a DOM node’s color to yellow and then fades it to white.

这道题好经典,涵盖了之前被问到的调色盘还有慢慢变大的button的各种知识点。