Closure is a very important feature of ECMAScript, but it is difficult to describe it with a suitable definition. Although closures are difficult to describe clearly, they are easy to create, or accidentally create. However, the existence of closures actually has certain potential problems. In order to avoid "accidentally" creating closures and to better take advantage of their advantages, it is necessary to understand the mechanics of closures.
Definition of closure
Regarding closure, there are too many definitions, especially some definitions are very abstract, like this one:
A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables.
Roughly speaking, closure is an expression that has some free variables and binds these variables execution environment. This definition is too literal and difficult to understand.
There is another definition:
All functions are closures. This definition confuses me a lot. In other words, since Javascript does not have block-level scope, closures generally refer to functions (I can’t think of any other ways to form closures other than functions).
I don’t want to discuss too much about the relationship between functions and closures here. Let’s give a definition that I think is easier to understand.
First of all, the existence of closures is based on the scope chain. Due to the scope chain mechanism, all functions (even global functions) can reference variables in the context execution environment (ie, free variables).
Secondly, there must be free variables inside the closure. By the way, there are two types of variables 1. Local variables (bound variables) 2. Non-local variables (free variables)
Finally, they still exist after their context ends. That is, the inner function has a longer life cycle than its outer function.
About the analysis of closure definition
Regarding the two points of closure definition, I have been considering whether they must be satisfied at the same time.
First of all, if there are no free variables inside the closure, that is to say, it does not access external variables, then the meaning of the closure is lost. (Unless the behavior is changed by other closures) Therefore, I think free variables are a requirement.
Secondly, if there are free variables inside the function, but when its context is destroyed, it will also be destroyed. It can be imagined that although the internal function accesses its external function variable, it is also recycled after the external function is executed. In this case, the discussion of closures is meaningless.
Let’s look at two examples:
闭包的优点和缺点
闭包的优点是闭包内部可以访问到定义它们的外部函数的参数和变量(除了this和arguments)。
闭包主要的问题便是它会保存包含它的函数的作用域,因此比一般函数占用更多的内存空间,因此不宜过度使用闭包。
闭包的应用
闭包最基本的应用场景便是通过保护内部变量从而实现私有,比如模块模式。