A brief introduction to javascript closures

This code has two features:

1. Function b is nested inside function a;

2. Function a returns function b.


In this way, after executing var c=a(), the variable c actually points to the function b, and after executing c() again, a window will pop up to display the value of i (the first time is 1). This code actually creates a closure, why? Because the variable c outside the function a refers to the function b inside the function a, that is:

  A closure is created when function b inside function a is referenced by a variable outside function a.

Example 1:


                      function f1() {    
				var n = 999;				    
				nAdd = function() {
					n += 1
				}			    
				function f2() {      
					alert(n);    
				}				    
				return f2;			  
			}			  
			var result = f1 ();			  
			result(); // 999			  
			nAdd();			  
			result(); // 1000

Example 2:


function outerFun()
 {
  var a=0;
  function innerFun ()
  {
   a++;
   alert(a);
  }    
 }
innerFun ()

The above code is wrong . The scope of innerFun() is inside outerFun(), it is wrong to call it outside outerFun().

Change it to the following, which is the closure:

js code

function outerFun()
{
 var a=0;
 function innerFun ()
 {
  a++;
  alert(a);
 }
 return innerFun; //Note here
}
var obj=outerFun();
obj(); //result is 1
obj(); //result is 2
var obj2 = outerFun ();
obj2(); //result is 1
obj2(); //result is 2

Example 3:


function outerFun()
{
 var a=0;
 alert(a);  
}
var a=4;
outerFun();
alert(a);

The result is  0,4  . Because the var keyword is used inside the function to maintain the scope of a inside outFun().

Look at the following code again:

js code 

function outerFun()
{
 // no var
 a =0;
 alert(a);  
}
var a=4;
outerFun();
alert(a);

It's weird that the result is  0,0  , why?

A scope chain is a term describing a path along which the value of a variable can be determined. When a=0 is executed, since the var keyword is not used, the assignment will follow the scope chain to var a=4; and change its value.

Notes on using closures

1) Because the closure will make the variables in the function are stored in the memory, the memory consumption is very large, so the closure cannot be abused, otherwise it will cause performance problems of the web page, which may lead to memory leaks in IE. The workaround is to delete all unused local variables before exiting the function.

2) The closure will be outside the parent function and change the value of the variable inside the parent function. So, if you use the parent function as an object, the closure as its public method, and the internal variable as its private value, be careful not to Casual

Change the value of a variable inside the parent function.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324685474&siteId=291194637