The concept of closures
What is a closure? Closure (Closure) is a function that refers to a free variable. This quoted free variable will exist with this function, even if it has left the environment in which it was created. So, there is another argument that closures are entities that are composed of functions and their associated reference environment.
In fact, in JS, each function is a closed packet. The function and its own internally defined variables are bound together, and the combined entity is the closure. Only in special cases, even if the function is done, for some reason the variables inside the function are still referenced by the outside world, so garbage collection does not release everything related to the function, and the function and necessary variables form a closed entity, not released, The closure is freed until there are no external variables that point to the internal variables of the current function.
Examples of closures
Example 1:
function Persion () {
var t = {};
T.name = "Itcast";
T.age = 19;
return t;
}
var p = new Persion ();
P.age;
function Persion () {
var ageprop = 19;
var nameprop = "Flydragon";
var phone = "110"; Private variables
function Getphone () {//define Property Get method
return phone;
}
function Setphone (value) {//define Property Set method
Phone = value | | "";
}
var showfun = function () {
Console.log (nameprop + "" + Ageprop);
};
return {
Age:ageprop,
Name:nameprop,
Show:showfun,
Get_phone:getphone,
Set_phone:setphone
};
}
var p = new Persion ();
P.show ();
Console.log (P.get_phone ());
Example 2: How do I let the parent function of a nested function access the inner variables of a child function?
function father () {
His.get_age = Child ();
function Child () {
var child_value = "Child";
return function () {
return child_value;
}
}
}
var f = new father ();
The child function has already been executed, but it can also access the value of the variable inside the child function.
F.get_age ();
Example 3: Global variables (or external variables)
function father () {
var get_value;
function Child () {
var child_value = 199;
Get_value = function () {
return child_value;
}
}
return {
Get:get_value;
}
}
var f = new father ();
F.get ();
Example 4:
function father () {
This.f_name = "Fater";
This.childage = Child ();
function Child () {
var c_age = 19; Private variables
return {
Set_age:function (value) {
C_age = value;
},
Get_age:function () {
return c_age;
}
}
}
}
var f = new father ();
F.childage.set_age (188);
Console.log (F.childage.get_age ());
Concepts and examples of closures