closure == function arguments
函数式参数(“Funarg”) —— 是指值为函数的参数。 可以翻译出来,很详细

概念 原理 实现 作用

透过作用域来看 闭包

When to use Closures?

Closures are a powerful concept given to JavaScript and some of the most common situations to use them are:


Allows us to hide the implementation details of a context from outside scopes, while exposing a controlled public interface. This is commonly referred to as the module pattern or revealing module pattern.


Perhaps one of the most powerful uses for closures are callbacks. JavaScript, in the browser, typically runs in a single threaded event loop, blocking other events from starting until one event has finished. Callbacks allow us to defer the invocation of a function, typically in response to an event completing, in a non-blocking manner. An example of this is when making an AJAX call to the server, using a callback to handle to response, while still maintaining the bindings in which it was created.

Closures as arguments

We can also pass closures as arguments to a function, which is a powerful functional paradigm for creating more graceful solutions for complex code. Take for example a minimum sort function. By passing closures as parameters, we could define the implementation for different types of data sorting, while still reusing a single function body as a schematic.

When not to use Closures ?

Although closures are powerful, they should be used sparingly due to some performance concerns:

Large scope lengths

Multiple nested functions are a typical sign that you might run into some performance issues. Remember, every time you need to evaluate a variable, the Scope Chain must be traversed to find the identifier, so it goes without saying that the further down the chain the variable is defined, the longer to lookup time.