|
What function is the closure? At the beginning of the study closure, it is able to are more difficult to understand. The official explanation from him for, are more conceptual.
But we still departing from the meaning of the closures.
Closure refers to functions have a free and independent variables. In other words, the definition of the closure function can "remember" when it creates the environment.
After the official explanation finished, let's look at a simple example of the count.
var c = 0;
function count () {
c ++;
}
count (); // 1
count (); // 2
This example is the use of global variables to achieve, but there is a problem, the variable c is also likely to be called by other means, which may change when the stored value of c. Cause the failure count count. That how well ! deal with this problem then we will think of is to use local variables such as the way to deal with:
function count () {
var c = 0;
function add () {
c ++;
}
add ();
}
count (); // c = 1
count (); // c = 1
Because after this creation, internal variables exist only in the count function to create executed, after performing, the whole function will be discarded. Can not be achieved with memory capacity. That to how to achieve it? That we use closures . I want to address once again mention: closure = function + environment
function count () {
var c = 0;
function add () {
c ++;
}
return add;
}
var ct = count ();
ct (); // c = 1
ct (); // c = 2
Capacity at this time we can through the closure to complete the count .ct closure is a function, the internal environment is the local variable c. Here we achieve is an internal data, external to the operation. The closure addition to this there What other functions?
Simulate private methods with closures
It's a bit like JAVA or private methods private variables can only allow ourselves to operate! If external operation, you need to set the method disclosed to operate.
var person = (function () {
var _name = "programming people";
var age = 20;
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 a public number: bianchengderen")
console.log (person.getName ())
It should be very easy to understand it! Somewhat object-oriented programming sense. Of course, now there are Javascript object-oriented programming features. This we later explained.
So far, we count from the interior to the example of privatization, to illustrate the closure, I hope you understand the simple truth, of course, there are other features closure use, it is more convenient. |
|
|
|