1. Definition and usage: When the return value of a function is another function, and if the returned function calls other variables inside its parent function, if the returned function is executed outside, a closure is generated.
2. Form of expression: enable the outside of the function to call the variables defined inside the function.
3. Examples are as follows:
(1) According to the rules of the scope chain, variables that are not declared in the underlying scope will be searched for the upper level, if found, they will be returned. Here obviously count is the count of flag2 inside the function.
var count=10; //The global scope is marked as flag1
function add(){ var count=0; //The function global scope is marked as flag2 return function(){ count+=1; //Inner scope of the function alert(count); } } var s = add() s(); // output 1 s(); // output 2
Case:
function f1(){ var n=999; function f2(){ alert(n); } return f2; } var result = f1 (); result(); // 999
4. The purpose of closure:
1) Get the internal variable . 2) Keep the internal variables in memory
function f1(){ var n=999; nAdd=function(){n+=1} function f2(){ alert(n); } return f2; } var result = f1 (); result(); // 999 nAdd(); result(); // 1000
In this code, result is actually the closure f2 function. It ran twice, the first time with a value of 999 and the second with a value of 1000. This proves that the local variable n in the function f1 has been kept in memory and is not automatically cleared after f1 is called.
5. Thinking questions
var name = "The Window"; var object = { name : "My Object", getNameFunc : function(){ return function(){ return this.name; }; } }; alert(object.getNameFunc()());
var name = "The Window"; var object = { name : "My Object", getNameFunc : function(){ var that = this; return function(){ return that.name; }; } }; alert(object.getNameFunc()());