英文原文 createAdder(x) is a function that returns a function. In JavaScript, functions are first-class objects: they can be passed to other functions as arguments and returned from functions as well. In this case, the function returned is itself a function that takes an argument and adds something to it.
Here’s the magic: the function returned by createAdder() is a closure. It “remembers” the environment in which it was created. If you pass createAdder the integer 3, you get back a function that will add 3 to its argument. If you pass 4, you get back a function that adds 4. The addThree and addFour functions in the above example are created in this way.
Let’s take another look at the addLoadEvent function. It takes as its argument a callback function which you wish to be executed once the page has loaded. There follow two cases: in the first case, window.onload does not already have a function assigned to it, so the function simply assigns the callback to window.onload. The second case is where the closure comes in: window.onload has already had something assigned to it. This previously assigned function is first saved in a variable called oldonload. Then a brand new function is created which first executes oldonload, then executes the new callback function. This new function is assigned to window.onload. Thanks to the magical property of closures, it will “remember” what the initial onload function was. Further more, you can call the addLoadEvent function multiple times with different arguments and it will build up a chain of functions, making sure that everything will be executed when the page loads no matter how many callbacks you have added.
Closures are a very powerful language feature but can take some getting used to. This article on Wikipedia provides more in-depth coverage.
在這裡,Äôs the magic:由createAdder返回函數()是一個閉包。它,Äúremembers,非盟在創建它的環境。如果傳遞createAdder整數3,你回來一個函數,將增加3至其參數。如果你通過四,你回來一個函數,增加了4。該addThree在上面的例子addFour職能創造這樣的。