To figure out a closure, you must first understand the scope of the variable: global (variable), local (variable). Global variables that can be read directly wherever you are:
var n = 123function me () { alert (n);} me (); // must pop 123
Instead of defining a variable inside the function, the outside of the function is naturally not available:
function Me () { var n = 123;} alert (n); // Error
Of course, learned JS know that if you declare a variable inside a function without Var, it is equivalent to declaring a global variable externally:
function Me () { = 123;} Me (); alert (n); // can pop up 123 because the variable n is actually a global variable
So is there any way we can read the internal variables externally? That's the closure, which is a special function: first define a function inside the function body:
function Me () { var n = 123; function You () { ///123 Because me is the parent function of you, naturally you can get your father's property;} }
Such nesting, embodies the JS language chain scope of the characteristics, that is, the parent function (parent object) All variables are visible to the child function, but the reverse is not possible, like a disobedience, and then external to the internal variables, only need to return the child function
function Me () { var n = 123; function You () { ///123 Because me is the parent function of you, naturally you can get your father's property; } return you ;} var our =// 123
This, the disobedience of the conspiracy to succeed!
About the application of closures, I will gradually update to the blog!!
About JavaScript closures