vardb =(function () {//Create a hidden object, this object holds some data//This object cannot be accessed from outside.vardata = {};//Create a function that provides some way to access datareturnfunction (key, Val) {if(val = = = undefined) {returnData[key]}//Get Else{returnData[key] = val}//Set }//We can call this anonymous method//return this intrinsic function, which is a closed packet}) ();d B ('x');//Back to undefineddb'x',1);//set data[' x '] to 1db'x');//returns 1//We can't access data, the object itself .//but we can set up a member of it
1. When a function is nested within a function, the internal function can access the variables in the external function.
2. External variables (environment variables?) ),
Including:
2.1 Global variables, including DOM.
2.2 Variables or functions for external functions.
If a function accesses its external variables, it is a closed packet.
Technically, in JS, each function is a closure, because it always has access to the data defined outside it.
Closed Package without return:
function Closureexample () { var; SetTimeout (function () { Console.log (+ +temp) ; + ); } Closureexample ()
Closure instances:
Function Demo () { var5; function Add () { Console.log (temp+ +) ; } return add; } var demeinstance = demo (); // the console demeinstance,temp has been added
JS Closure Example