var num = someNum; var anArray = [1,2,3]; var ref = someRef; returnfunction(x) { num += x; anArray.push(num); alert(num+anArray.toString()+ref.someVar); } } closure1=newClosure(40,{someVar:'closure 1'}); closure2=newClosure(1000,{someVar:'closure 2'});
closure1(5); // num:45 anArray[1,2,3,45] ref:'someVar closure1' closure2(-10);// num:990 anArray[1,2,3,990] ref:'someVar closure2' //5 functionsayAlice() { var sayAlert = function() { alert(alice); } // Local variable that ends up within closure var alice = 'Hello Alice'; return sayAlert; } var helloAlice=sayAlice(); helloAlice(); //6 functionsetupSomeGlobals() { var num = 666; gAlertNumber = function() { alert(num); } gIncreaseNumber = function() { num++; } gSetNumber = function(x) { num = x; } } setupSomeGolbals(); // 为三个全局变量赋值 gAlertNumber(); //666 gIncreaseNumber(); gAlertNumber(); // 667 gSetNumber(12);// gAlertNumber();//12 //7 functionsay667() { var num = 666; var sayAlert = function() { alert(num); } num++; return sayAlert; }
var sayAlert = say667(); sayAlert() //8 单例模式下的闭包应用 </script> </body> </html>