JavaScript Learning Notes (11)--closures

Source: Internet
Author: User
Tags closure pow variable scope

In the study of Liaoche predecessors of the JavaScript tutorial, encountered some points needing attention, so as a study notes listed, remind yourself to notice!

If you have the need, welcome to visit the previous blog https://www.liaoxuefeng.com/ study.

Scope of the variable

To understand closures, you must first understand the special variable scope of JavaScript.

The scope of a variable is nothing more than two kinds: global variables and local variables.

The special point of the JavaScript language is that the global variables can be read directly inside the function .

var n=999; function  //  999

On the other hand, a local variable inside a function cannot be read naturally outside the function .

function F1 () {  var n=999//  error

It is important to note that you must use the var command when declaring a variable inside a function, and if not, you are actually declaring a global variable.

function F1 () {n=999//  999
How to read local variables from outside

For various reasons, we need to get local variables inside the function. Under normal circumstances, it is impossible, but we have other ways to get it.

That is, in the inside of the function, define a function.

function  F1 () {  var n=999;  function//  999  }}

In the above code, the function F2 is included inside the function F1, when all local variables inside the F1 are visible to the F2. But the opposite is not possible, F2 internal variables, the F1 is not visible. This is the chain scope structure that is unique to the JavaScript language, and the sub-object looks up the variables of all the parent objects one level at a level. Therefore, all the variables of the parent object are visible to the child object, and vice versa.

Since F2 can read the local variables in the F1, then just take F2 as the return value , we can not read its internal variables outside the F1!

  function    F1 () {  var n=999;      function  f2 () {alert (n);  }  return  F2; }  var result=//  999
The concept of closures

The F2 function in the above code is the closure.

Because in the JavaScript language, only sub-functions inside the function can read local variables, it is possible to simply interpret the closure as "a function defined inside a function".

So, in essence, a closure is a bridge that connects the inside of the function to the outside of the function.

use of closures

Closures can be used in many places. Its maximum usefulness is two, one of the previously mentioned variables that can read the inside of a function , and the other is to keep the values of these variables in memory at all times .

  function    F1 () {  var n=999;    Nadd=function() {n+=1}  function  f2 () {alert (n);  }  return  F2; }  var result=//  999//  

In this code, result is actually the closure F2 function. It runs altogether two times, the first value is 999, the second value is 1000. This proves that the local variable n in the function F1 is kept in memory and is not automatically cleared after the F1 call.

Why is that?

The reason is that F1 is the parent function of F2, and F2 is assigned to a global variable, which causes F2 to always be in memory, and F2 's presence depends on F1, so F1 is always in memory and will not be reclaimed by the garbage collection mechanism (garbage collection) after the call ends.

Another notable part of this code is the line "nadd=function () {n+=1}", which first did not use the var keyword in front of Nadd, so Nadd is a global variable, not a local variable. Second, the value of Nadd is an anonymous function (anonymous functions), and the anonymous function itself is a closure, so nadd is equivalent to a setter that can manipulate local variables inside the function outside of the function.

In object-oriented programming languages, such as Java and C + +, to encapsulate a private variable inside an object, you can use private a member variable to decorate it.

In the absence class of a mechanism, only the language of the function, with closures, can also encapsulate a private variable. We create a counter with javascript:

' Use strict '; function Create_counter (initial) {    var x = Initial | | 0;     return {        function  () {            + =1            ; return x;}}    }

It used to look like this:

var c1 =//  1//  2//  3var c2 = Create_ Counter (Ten//  //  //   )

In the returned object, a closure is implemented that carries the local variables and that the variables are inaccessible x from external code at all x . In other words, a closure is a function that carries state, and its state can be completely hidden from the outside.

math.pow (x, y) function, but given the frequent calculation of X2 or x3, we can use closures to create new functions pow2 and pow3 :

' Use strict '; function Make_pow (n) {    returnfunction  (x) {        return  math.pow (x, n);    }}//  Create two new functions:var pow2 = Make_pow (2); var pow3 = Make_pow (3); Console.log (Pow2 (/   /// 343 
Note points for using closures

1) Because the closure will make the variables in the function are stored in memory, memory consumption is very large, so can not abuse closures, otherwise it will cause the performance of the Web page, in IE may cause memory leaks. The workaround is to remove all unused local variables before exiting the function.

2) The closure changes the value of the inner variable of the parent function outside the parent function. So, if you use the parent function as an object, and the closure as its public method, and the internal variable as its private property (private value), be careful not to arbitrarily change the value of the inner variable of the parent function.

JavaScript Learning Notes (11)--closures

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.