What is a closure function? At the beginning of the closure of the study, it is very difficult to understand. As far as his official explanation is concerned, it is more conceptual.
But we still start with the meaning of closures .
A closure is a variable in which a function is free and independent. In other words, a function defined in a closure can "memorize" the environment in which it was created.
After the official explanation, let's take a look at a simple counting example.
var c = 0;
function count () {
C + +;
}
Count ();//1
count ();//2
This example is implemented using a global variable, but here's the problem with C, which can be easily invoked by other means, which may change the storage value of C. Causes this count count to fail. How to deal with this problem very well! We will think of the use of local variables in the way to deal with. For example:
function count () {
var c = 0;
function Add () {
C + +;
}
Add ();
}
Count ();//c = 1
count ();//c = 1
Because after this creation, the internal variable exists only when the Count function is created and executed, and the entire function is discarded. There is no ability to remember. How does that come about? So we're going to use a closure. I want to mention it again: closure = function + Environment
function count () {
var c = 0;
function Add () {
C + +;
}
return add;
}
var ct = count ();
CT (); c = 1
ct ();//C = 2
This is the time when we can do the counting with this closure. CT is a closure function, the internal environment is this local variable C. What we have here is internal data, external operations. What other functions does the closure have besides this?
Simulating private methods with closures
This is a bit like a Java private method or a private variable that can only allow itself to operate! If external operations, you need to set the open method to operate.
var person = (function () {
var _name = "Programmer";
var age =;
return {
add:function () {
age++;
},
jian:function () {
age--;
},
getage:function () { return age
;
},
getname:function () {return
_name;
},
setname:function (name) {
_name = name;}}
) ();
Person.add ();
var age = Person.getage ();
Console.log (age)
Person.setname ("Programming person public Number: Bianchengderen")
Console.log (Person.getname ())
It should be easy to understand here! Some sense of object-oriented programming. Of course, JavaScript now has the characteristics of object-oriented programming. We'll explain this later.
So far, we have from the count to the internal privatization examples to illustrate the closure, I hope that we can understand the truth, of course, closures and other functional use is more convenient.
The above is the entire content of this article, I hope to learn JavaScript program to help you.