The concept and closure of the block-level scope of JavaScript

Source: Internet
Author: User
Tags closure garbage collection
Simple block-level scope:

JavaScript does not have a block level scope concept

function test () {for                          
	(var i = 1; I <=5; i++) {  //i     
		alert (i);                         
	}                                     
	alert (i);  6                        
}                                         
                                          
test ();                                   
The final output is 6.
I will be reclaimed by the garbage recovery mechanism only when test is completed.

To avoid this happening, you can use the inside for loop as a separate domain. Use function to include.

function test () {                             
	function () {for                             
		(var i = 1; I <=5; i++) {  //i    
			alert (i);                        
		}						             
	};                                    
	alert (i);                                
}                                            

But the function does not execute itself, in JS () indicates the execution

function test () {                              
	(function () {for                              
		(var i = 1; I <=5; i++) {  //i     
			alert (i);                         
		}						              
	}) ();                                     
	alert (i);                                 
}                                             
Test ();                                       
This will not have 6 output.

Use a function directly (functions () {...}) () Form can be executed directly.

(function () {alert (' I executed directly! ');}) ();   

Closed Bag

In a programming language, a closure is a paragraph in which a grammar field is located in a particular region and has a persistent reference (read and write) to a Non-persistent variable value capability on an execution field that is outside its own scope. The non-persistent variables of these external execution fields magically retain their values when the closure was originally defined (or created).
The above explanation doesn't have to be fully understood (I just saw it), and look at the code directly below:

var name = "Xiao A";                    
var obj = {                             
      name: ' Xiao B ',                 
      getname:function () {return              
		function () {return              
			this.name           
		}                                   
}}} ;                                      
Alert (Obj.getname () ());			        
The result is not the output "Xiao B", but the "Xiao A" Reason:
When we alert (Obj.getname ()), the return result is: function () {
return this.name;
}

This time using Obj.getname () (), which is already in window, is in the outer layer of obj. Returning "Xiao A" is equivalent to the following code:

var name = "Xiao A";                    
var obj = {                             
      name: ' Xiao B ',                 
      getname:function () {return              
		function () {return              
			this.name           
		}                                   
}}} ;                                      
                                        
Alert (Obj.getname () ());			        
var k = Obj.getname ();  Global scope         
//alert (typeof k);//function Type        
alert (k ());                             
Output "Xiao A" as the result

If you want to output "Xiao B", you need a variable to hold the current caller's object.

var name = "Xiao A";                
var obj = {                         
      name: ' Xiao B ',             
      getname:function () {          
	  	//This always points to the caller              
		var o = this;               
		                            
		return function () {return          
			o.name;          
		}}}                               
;                                  
Alert (Obj.getname () ());	        
                                    
var k = Obj.getname ();              
Alert (k ());                         
Save Obj's This object with O, always point to the caller, the caller of GetName () is obj, so o represents obj, and the return is O.name


Closure is simpler: closures: A function can access variables in the scope of another function

Closure Example:

function f (x) {//assumed to be Level 2 scope var temp = x; Local variable//temp has not been used by return function (x) {//Level 3 scope (function has an execution domain var obj) temp		+ = x;						                       
		     was also used alert (temp);				                                                           
}                                                             
}                                                             
var a = f (50);                                                                
                                                                           
alert (a);				                                                       
A (5);                                                                     
A (10);			                                                           A (20); 
When I call F (50) temp=50, return function (x) {Temp+=x;alert (temp);} and assigned to a. Then execute a (5) and output 55. Then execute a (10) and output 65. Then execute a (20) and output 85.

When I return assignment to a, the scope and F (x) scopes are the same, the TEMP variable in F can not be accessed according to the general term, and the TEMP variable will be retracted by the garbage collection mechanism, but this is not the case when the garbage collection mechanism detects that the return function will continue to be checked after the temp is used. The discovery function inside the continue to use temp, will again Mark temp is used.

When a (5) is invoked, the "a" function is detected and the TEMP variable is used, so the TEMP variable is tagged again and will not be reclaimed.

The simple understanding is this: this is the equivalent of accessing the TEMP variable in the F function in a function.






Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.