Understanding JavaScript Closures

Source: Internet
Author: User
Tags variable scope

The scope of a 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. On the other hand, a local variable inside a function cannot be read naturally outside the function. (Here's a place to be aware that when declaring variables inside a function, be sure to use the var command.) If not, you're actually declaring a global variable! )

Second, how to read the local variables from the outside?

For a variety of reasons, we sometimes need to get local variables within the function. However, as already mentioned, normally, this is not possible, only through the workaround to achieve: that is inside the function, and then define a function.

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

Third, JS closed package

The official explanation for closures is that an expression (usually a function) with many variables and environments that bind these variables is also part of the expression.

Features of closures:

1, as a reference to a function variable, when the function returns, it is in the active state.

2, a closure is when a function returns, a stack that does not release resources.

To put it simply, JavaScript allows the use of intrinsic functions-that is, function definitions and function expressions in the function body of another function. Furthermore, these intrinsic functions can access all local variables, arguments, and other intrinsics declared in the outer function in which they are located. When one of these intrinsics is called outside the outer function that contains them, a closure is formed.

function Closure () {    var'I ' m a part variable. " ;     return function () {        alert (str);    }} var fobj = closure (); Fobj ();

In the above code,Stris defined in the functionclosure local variables, if str in closure can no longer be accessed after the function call is completed, then str will be released. But because the function closure returned an intrinsic function, And this returned function references the str variable, resulting in str may be < Span style= "font-family:"times New roman"" >closure function is also referenced after execution, so str is not recycled.

In this way the closure form a closure.

  In fact, when we add the Get/set function to a private variable in a custom JavaScript class, we've used a closure.

function Class1 () {   var  vari;    this. Getvari = function () {return  vari;}    this. Setvari = function (_vari) {vari =varnew  Class1 (); Cls.setvari (  "test variable"); alert (Cls.getvari ());

In this example, the constructor defines the variable vari, which is recycled if vari is not referenced by another member method that can be applied externally, after the constructor execution is finished. But after we have defined the Get/set function for it, because these two intrinsics can be accessed by the outside of the Class1 (class) containing their function, and the variable vari is referenced by the two functions, vari is not recycled. This creates a closure.

The principle of JavaScript garbage collection is that if an object is no longer referenced, the object will be reclaimed by the garbage collector. If two objects have no interfering references to each other, then both objects are recycled.

Iv. use of closures

Closures play an important role in JavaScript programming and, if used properly, can bring a lot of convenience to the solution of some problems. But if the use is inappropriate, it can cause a lot of trouble.

1. Provide parameters for the executed function.

SetTimeout can defer execution of a function, and the prototype is as follows: SetTimeout (CODE,MILLISEC). The first parameter is the function or code that needs to be executed, and the second parameter is the number of milliseconds to delay. Common usage:

function SayHello () {alert ("helloWorld");} SetTimeout (SayHello,+);

But maybe we'll need a generic function, not just "Hello World". We write a say () function that gives say the parameters to pass a message that needs to be said. However, in settimeout we cannot pass parameters to functions that require deferred execution. With closures, we can do this:

function Say (words) {       return  function () {           alert (words)       }   }      setTimeout ( Say ("Hello Word"),+);   SetTimeout (Say ("I ' m hungry,i ' m need some food! "),

This allows parameters to be passed to functions that require deferred execution when calling SetTimeout.

2. Simulating static private variables

JavaScript does not natively support object-oriented features. But we can implement JavaScript object-oriented through some JavaScript feature simulation. For example, we need to define a class and simulate static private variables.

varClass2 =(function () {varS_var =0;//Static Private variables       returnfunction () { This. Getinstancecount =function () {returnS_var; }           //Constructors_var++; }   })()      varCLS1 =NewClass2 ();   Console.log (Cls1.getinstancecount ()); //1      varCLS2 =NewClass2 ();   Console.log (Cls1.getinstancecount ()); //2Console.log (Cls2.getinstancecount ());//2      varCLS3 =NewClass2 ();   Console.log (Cls1.getinstancecount ()); //3Console.log (Cls3.getinstancecount ());//3

In this example, we use S_var to record the number of times Class2 is instantiated, using closures, we can simulate S_var as a static private variable, and each time the CLASS2 is instantiated, the S_var is added 1.

In the example above, we used a piece of code that defines an outer layer function in which members outside the inner layer function are similar to static members. So in this form of code we can call him "static packaging environment".

(function () {       return  function () {};}) ()

Understanding JavaScript 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.