[Go] javascript closures

Source: Internet
Author: User

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.
Simply put, 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, STR is defined as a local variable in the function closure, and if STR cannot be accessed after the completion of the closure function call, STR will be freed after the function is executed. However, because the function closure returns an intrinsic function, and the returned function references the STR variable, the STR may be referenced after the closure function is completed, so the resources used by STR are 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 = _vari;}   }     var New 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.

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 function being executed.
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. Associating an object's method with another instance

For example, we are doing a multi-file upload program that requires the ability to dynamically add and delete files:

function AddFile () {varFileInput = Document.createelement ("input"); Fileinput.type="file"; Fileinput.name="file"; varBtndel = Document.createelement ("input"); Btndel.type="Button"; Btndel.value="Delete"; Btndel.onclick=(function () {//Deleting Files                returnfunction () {varc = _ ("filecontent");                    C.removechild (FileInput);                C.removechild (Btndel);                    }          })(); varFcontent = _ ("filecontent") Fcontent.appendchild (fileInput);       Fcontent.appendchild (Btndel); }
View Code

In this example, we delete the corresponding upload form and the button itself in the function associated with the click time of the Delete button. Since forms and buttons are both dynamically generated, it is not known beforehand what the deleted button needs to be deleted. But we can use JavaScript closures to correlate the click events of the button with the upload form instance and the button instance when uploading the form and button generation.

3. 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 ();   Alert (Cls1.getinstancecount ()); //1      varCLS2 =NewClass2 ();   Alert (Cls1.getinstancecount ()); //2Alert (Cls2.getinstancecount ());//2      varCLS3 =NewClass2 ();   Alert (Cls1.getinstancecount ()); //3Alert (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 () {       }         }) ()

Reference article Address:

Http://baike.baidu.com/view/648413.htm
Http://www.cnblogs.com/yangjian/archive/2009/09/24/1573176.html
http://www.cnblogs.com/chongzi/
Http://www.360doc.com/content/09/1227/11/370235_12087397.shtml
Http://softbbs.pconline.com.cn/9497825.html

[Go] 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.