On the function expression of JavaScript (closure)

Source: Internet
Author: User
Tags closure

The previous article has simply introduced the closure of the function. The closure of a function is a function that has access to another function scope, which in turn defines a function inside the function.

1 varSuper=function(num) {2                         varCount=num;3                         return function(){4 Console.log (count);5                         }6                     }7                     varResult=super (3);//at this point, result is a function8Result ();//Output 3

The above code defines a function super, which in turn defines an anonymous function as the return value inside the Super function. Line seventh calls the Super function, at which time result is a function. Line 8th executes the result function, and the output is 3. This is the embodiment of the closure, because the super function above has been executed, but its internal variable count value is still not released, Count is still being referenced by anonymous function, so there is no way to release. If you want to free count, we need to result=null to assign a null value to result.

The scope chain of the function has been introduced in the previous article, and when the function is first called, a scope chain is created and the scope chain is assigned to a special internal property. In a scope chain, the active object of the function's outer function is in the second position, the active object of the external function of the outer functions is in the third position, and so on, the scope chain of the global variable is at the bottom.

1 varcount=2;2Console.log (count);//23Count=3;4Console.log (count);//35 varSuper=function(num) {6 varCount=num;//scope chain Second bit7Console.log (count);//18 return function(){9 varcount=5;//The first bit of the scope chainTen Console.log (count); One } A } - varresult=NewSuper (1); -Result ();//Output 5

The scope of the variable can be clearly understood in the code above. The inner variable of the closure function is at the top, and the global variable is at the bottom.

The use of this object in closures can also cause some problems when the This object is bound to a function-based execution environment when the function is run. In the global function, this points to the Window object. When a function is called as an object, this is equal to that object. However, the execution environment for anonymous functions is global, so this points to the window

1 varobj={2Name: "Heh",3GetName:function(){4                             varthat= This;5                             return function(){6                                 returnThat.name;7                             }8                         }9                     };Ten                     varOne=obj.getname (); One                     varName=one ();//heh

In the above code, the object obj is created by literal means, defining the object's property name and method GetName. But inside the getname, we define the closure function. If you want to access the name in the closure function, you cannot access it through this. So you need to define a variable from the outside of the closure function, which points to this. Variables defined in the GetName can still be used in the closure function.

There is no concept of block-scoped scope in JavaScript, which means that variables defined in the block level are actually available inside the function.

1  for (var i=0;i<10;i++) {2                        console.log (i); 3                     }4                     console.log (i);   output Ten

In the above code, we define the variable i in the For loop, but we can still use I outside of the For loop. After the for Loop has ended, the I variable is not destroyed.

JavaScript can use anonymous functions to mimic block-level scopes to avoid the occurrence of such problems.

  

1 (function() {2for                         (var i=0;i<10;i++) {  3                            console.log (i); 4                         }5                    }) (); 6                     Console.log (i);

In the above code, we put the block-level scope in an anonymous function and put the anonymous function in a pair of parentheses, which represents a function expression. The parentheses outside the function expression indicate that the function is called immediately. When the function is called on line sixth, an error occurs because I is not defined.

  

1 var testfunc=function() {2for                         (var i=0;i<10;i++) {3                            console.log (i); 4                         }5                    }; 6                     TestFunc (); 7                     Console.log (i);

This code, like the code above, is defined by a function expression.

  

1 function () {2                          for (var i=0;i<10;i++) {3                            console.log (i); 4                         }5                     } ();

The above code is wrong. We know the definition of a function, which can be expressed through functions and function expressions. Functions can be declared by function and cannot be followed by parentheses. function expressions can be followed by parentheses.

  

1 var testfunc=function() {2for                         (var i=0;i<10;i++) {3                            console.log (i); 4                         }5                     } ();

In general, you should add functions and variables to the global object as little as possible during the development process. Too many global functions and variables tend to cause naming conflicts and memory leaks. We can do all of the work in block-level functions.

  

1 (function() {2                         varnew  Date (); 3                         Console.log (Now.getfullyear () + "-" + (Now.getmonth () +1) + "-" +now.getdate () + "" +now.gethours () + ":" +now.getminutes () + ":" +now.getseconds ()); 4                     }) ();

Through the code above, we are able to present the date and time.

On the function expression of JavaScript (closure)

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.