Definition of closures
Closures are variables that have free and independent functions. In other words, a function defined in a closure can "remember" the environment it was created in.
The superficial understanding of closures
function Makefunc () { var name = "Mozilla"; function DisplayName () { alert (name); } return displayName;} var myFunc = Makefunc (); MyFunc ();
This code looks awkward but works fine. In general, local variables in a function are only available during the execution of a function. Once makeFunc() executed, it is reasonable to assume that the name variable will no longer be available. Although the code works fine, it's not.
The answer to this puzzle is to myFunc become a closure . Closures are a special kind of object . It consists of two parts: a function , and the environment in which the function is created. An environment consists of any local variables that are in scope when the closure is created. In our case, myFunc it is a closure, formed by the displayName "Mozilla" string that exists when the function and the closure are created.
For a better understanding of this sentence, simply look at:
Closures can implement private variables.
function Animal (type) { var data = []; data[' type '] = type; This.gettype = function () { return data[' type '];} } var fluffy = new Animal (' dog '); Fluffy.gettype (); Back to ' dog '
In this example, a local array of data is created in the animal class. When the animal object is instantiated, a value of type is passed and the value is placed in the data array. Because it is private, the value cannot be overwritten (the animal function defines its scope). Once an object is instantiated, the only way to read the type value is to call the GetType method. Because GetType is defined in animal, GetType can be entered into data with the closure generated by the animal. In this case, the type of the object can be read but cannot be changed. This is a bit like having a private set accessor in C # and implementing the injected property through a constructor function. In this sense, the function of JavaScript is closure.
The role of closures
It is simply a definition that surrounds it:
1. You can save a separate variable. Because the scope of the inner function of the closure is only present inside the function, the variable is guaranteed to be secure.
2. Functions defined in closures can "remember" the environment in which it was created. In layman's words, when a function in a closure is assigned to a variable outside the closure, its reference points to the external temporary variable. As long as this referential relationship persists, the environment at the time the closure is created is saved. You can indirectly maintain the value of the temporary variable used by the original constructor body.
JavaScript memos-Closures (2)