//1 definition and use of anonymous functions//1.1 Assigning an anonymous function to a variable is performed by a variablevarbox =function() { return"Lee";} Box (); //"Lee"//1.2 Performing anonymous functions by self-executing//( anonymous function) ();(function() { return"Lee";}) (); //"Lee"//1.3 anonymous function self-reference(function(age) {returnAge ;}) (100);// -//2 Closures//2.1 Packet Closure functionfunctionbox () {return function() { return10; }}box (); //See below/*function () {return;}*/box () ();//Ten//2.2 Returning local variables via closuresfunctionbox () {varAge = 100; return function() { returnAge ; };} Box (); //See below/*function () {return age;}*/box () ();// -//2.3 Using anonymous functions to implement local variables residing in memory to accumulatefunctionbox () {varAge = 100; return function() { age++; returnAge ; }}varb =box (); B ();//101b ();//102b ();//103//destroying references waiting for the garbage collector to clean upb =NULL;//2.4 About closures the This object//window is the largest global object in JS .//this is different in different scopes but points to the object itself//This refers to the window object This;//Window {...} This. Name = "Window";varbox ={name:"Box", GetName:function() { return function() { //inside the closure function this refers to the Window object return This. Name; }}}box.getname () (); //"Window"//Object ImpersonationBox.getname (). Call (Box)//"box"varbox ={name:"Box", GetName:function() { //outside the closure function this refers to the box object varthat = This; return function() { returnThat.name; }}}box.getname () (); //"box"
JavaScript anonymous functions and closures