Anonymous Functions and Closures for javascript Notes

  • 2021-07-16 01:50:20
  • OfStack

This article introduces js anonymous functions and closures for your reference, the specific content is as follows

Anonymous function


<script type="text/javascript"> 
 //function(){}// Will report an error  
 var fun = function(){};// Assign anonymous functions to variables  
 
 (function(){})();// Anonymous function self-execution  
 
 function(){ 
 return function(){};// Anonymous function in function  
 } 
</script> 

Closure

A closure is a function that has access to variables in the scope of another function. A common way to create a closure is to create another function within a function and access its local variables through the other function


<script type="text/javascript"> 
 // You can return local variables through closures  
 function box() { 
 var user = 'Lee'; 
 return function () { // Returns through an anonymous function box() Local variable  
  return user; 
 }; 
 } 
 console.log(box()());  // Pass box()() To directly call the anonymous function to return the value  
 var b = box(); 
 console.log(b());  // Another 1 Call the return value of anonymous function  
 
 // Accumulation of local variables can be realized by closure  
 function box() { 
 var age = 100; 
 return function () { 
  age ++; 
  return age; 
 } 
 } 
 var b = box();  // Obtain function  
 console.log(b());  // Call anonymous function  
 console.log(b());  // No. 1 2 Call the anonymous function for the next time to realize accumulation  
</script> 

Using closures has one advantage and one disadvantage: It allows local variables to reside in memory and avoids using global variables. Global variable contamination leads to application unpredictability, and every module can be called, which will lead to disaster. Therefore, private and encapsulated local variables are recommended. Because the local variable resources returned by the scope in the closure will not be destroyed and recycled immediately, it may occupy more memory. Overuse of closures can lead to performance degradation, and it is recommended to use closures only when it is very necessary.

Closure in loop


<script type="text/javascript"> 
 function box() { 
 var arr = []; 
 
 for (var i = 0; i < 5; i++) { 
  arr[i] = function () { 
  return i; 
  }; 
 } 
 return arr; 
 } 
 
 var b = box();    // Get an array of functions  
 console.log(b.length);   // Get the length of function set  
 for (var i = 0; i < b.length; i++) { 
 console.log(b[i]());   // Output the value of each function, which is the last 1 Values  
 } 
</script> 

box () has been executed, i has already changed to 5, and the returned function holds all variables i, so the final result is 5 5

Closure in Loop--Modification


<script type="text/javascript"> 
 function box() { 
 var arr = []; 
 
 for (var i = 0; i < 5; i++) { 
  arr[i] = (function (num) { 
  return function () {  // Return function  
   return num; 
  } 
  })(i); 
  /* 
  // Equivalent to : 
  arr[i] = (function () { 
  var num = i;// Definition 1 Local variables  
  return function () { 
   return num; 
  } 
  })(); 
  */ 
 } 
 return arr; 
 } 
 
 var b = box();    // Get an array of functions  
 for (var i = 0; i < b.length; i++) { 
 console.log(b[i]());   //0,1,2,3,4 
 } 
</script> 

By creating a new block-level scope in the box scope, the variables saved by each return function are different

this Objects in Closures

Closures, on the other hand, point to window's at run time, because closures do not belong to properties or methods of this object.


<script type="text/javascript"> 
 var user = 'The Window'; 
 
 var obj = { 
 user : 'The Object', 
 getUserFunction : function () { 
  return function () { // Closure does not belong to obj , inside this Point window 
  return this.user; 
  }; 
 } 
 }; 
 console.log(obj.getUserFunction()()); //The window 
 // You can force a point to an object  
 console.log(obj.getUserFunction().call(obj)); //The Object 
 /* 
 // It can also be from the top 1 Objects are obtained in a scope  
 getUserFunction : function () { 
 var that = this;  // Object from Object's Method  
 return function () { 
  return that.user; 
 }; 
 } 
 */ 
</script> 

Mimic block-level scope

JavaScript has no scope for block-level statements, if () {} for () {} and so on have no scope


<script type="text/javascript"> 
 // Use block-level scope ( Private scope ) Rewrite  
 function box(count) { 
 (function () { 
  for (var i = 0; i<count; i++) {} 
 })(); 
 console.log(i); // Error reported, unable to access  
 } 
 box(2); 
</script> 

When block-level scopes (private scopes) are used, any variables defined in an anonymous function are destroyed at the end of execution. Using block-level scoping in global scope reduces the memory footprint of closures because there are no references to anonymous functions. As soon as the function is finished, its scope chain can be destroyed immediately.

Private variable

JavaScript does not have the concept of private attributes; All object properties are public. However, there is a concept of a private variable. Any variables defined in a function can be considered private because they cannot be accessed outside the function

By creating a closure inside the function, the closure can also access these variables through its own scope chain. Using this point, you can create public methods for accessing private variables.


<script type="text/javascript"> 
 function Box() { 
 var age = 100;   // Private variable  
 function run() {   // Private function  
  return ' In operation ...'; 
 } 
 this.get = function () {  // External public privileged method , Closure (the function accesses the age And run Method)  
  return age + run(); 
 }; 
 } 
 
 var box = new Box(); 
 console.log(box.get()); 
</script> 

Static private variable

The above private variables are reinitialized each time the object is instantiated. By defining private variables or functions in block-level scope (private scope), you can also create privileged methods that are public to the outside world. .


<script type="text/javascript"> 
 (function () { 
 var age = 100;// Static private variable  
 function run() { 
 return ' In operation ...'; 
 } 
 Box = function () {}; // Constructor, without using the var Global function  
 Box.prototype.go = function () { // Prototype method  
 return age + run(); 
 }; 
 })(); 
 
 var box = new Box(); 
 console.log(box.go()); 
</script> 

Modular mode


<script type="text/javascript"> 
 var box = function () { //box Yes 1 Modules  
 var age = 100; 
 function run() { 
 return ' In operation ...'; 
 } 
 return { // Returns an object directly  
 go : function () { 
 return age + run(); 
 } 
 }; 
 }(); 
</script> 

Related articles: