JS closure essays are welcome to Fu Zheng

The concept of:
Closure of the internal function variables of external functions in the domain, and returns the internal functions, the variables are called free variables, also called closure variables. Even if the return to the external function, because the internal function indirect reference the variable, when the GC is not related to the object. When it is used, will release the resources.

//(1)
         function (n) {
             alert(n);
         } (3); //No effect
         //(2)
         (function (n) {
             alert(n);
         })(3); //Will pop up 3
         //(3)
         var b = function (n) {
             alert(n);
         } (3); //Will pop up 3
         //(4)
         var b1 = function (n) {
             alert(n);
         }
         b1(3); //Will pop up 3
         /*In the code above, I can come from
         1.(1)And (2) the difference between (1) did not perform, (2) execution.
         2.()That allow the anonymous function is executed immediately
         */


/*
         The following code Result1 and Result2 output results are what.
         The result is certainly not the same
         The output of Method1: is: 1-9
         The output of Method2: is: 9 10
         Why this is so.
         You can consider just the appetizer in Demo.
         Below we look at the Method1.
         (function (m) {
                     return m;
                 })(i);
         This anonymous function returns the result value after operation, and then assigned to array
         Next we see in Method2
         array[j] = function () {
                     return j;
                 };
            Refer to the function of the array gain, the function is not implemented
         */
         function CreateArray1() {
             var array = new Array();
             for (var i = 0; i <10; i++) {
                //Difference
                 array[i] = (function (m) {
                     return m;
                 })(i);
             }
             return array;
         }
         var results1 = CreateArray1();
         document.write("Method1 Results:<br/>");
         for (var i = 0; i <results1.length; i++) {
             document.write(results1[i]+"<br/>");
         }
         document.write("------------------------<br/>");
         document.write("Method2  Results:<br/>");
         function CreateArray2() {
             var array = new Array();
             for (var j = 0; j <10; j++) {
                 //Difference
                 array[j] = function () {
                     return j;
                 };
            }
            return array;
        }
        var results2 = CreateArray2();
        for (var i = 0; i <results2.length; i++) {
            document.write(results2[i]() + "<br/>");
        }



<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
     <script type="text/javascript">
         /*
            When I click on example 1, example 2, example 3 times respectively, pop 1,2,3
            The following code: 
            But the code does not have the effect I want, but click on all the "example" are 4
            The reason is that the closure caused. Function of each click onclick to use is alert()
            When the end of a cycle, the alert () function returns the value is the maximum value.
            How to solve this problem.
            See func2()
            //How to understand this word(function (n) { return function () { alert(n) }; })(v), 
            Immediately the execution of the current function, the example of onclick reference function is function () {alert (n)}, n value is the current value of V
         */
         function func1() {
             var v;
             for (var i = 1; i <5; i++) {
                 v = i;
                 document.getElementById('closureExample' + v).onclick = function () { alert(v) };
             }
         }
         function func2() {
             var v;
             for (var i = 1; i <5; i++) {
                 v = i;
                 document.getElementById('closureExample' + v).onclick = (function (n) { return function () { alert(n) }; })(v);
             }
         }
         window.onload = function () {
             //func1();
             func2();
         }
    </script>
</head>
<body>
<a href="#" id="closureExample1">Example 1</a>
<a href="#" id="closureExample2">Example 2</a>
<a href="#" id="closureExample3">Example 3</a>
<a href="#" id="closureExample4">Example 4</a>
</body>
</html>

Started by Daniel at February 01, 2016 - 8:09 AM

BLOG

Posted by Daniel at February 16, 2016 - 8:39 AM

Learning to learn

Posted by Constance at March 01, 2016 - 9:23 AM

A func2 can also be written as
<body>
<a href="#" id="closureExample1">Example 1</a>
<a href="#" id="closureExample2">Example 2</a>
<a href="#" id="closureExample3">Example 3</a>
<a href="#" id="closureExample4">Example 4</a>
<script type="text/javascript">
        function func2() {
             var aCollection = document.getElementsByTagName("a");
             for(var i=0;i<aCollection.length;i++){
                aCollection[i].onclick=(function(n){
                    return function(){alert(n+1);}
                })(i)
             }
         }
        func2();
</script>
</body>

Posted by Jimmy at March 13, 2016 - 9:53 AM

Can not for onclick in the setting of func2 internal variable internal call.

Posted by Jimmy at March 20, 2016 - 10:46 AM

Thanks
You don't have much difference with my code is a meaning

Posted by Daniel at March 27, 2016 - 11:33 AM

A bit dizzy, learning

Posted by Debra at April 10, 2016 - 12:23 PM

Next to

Posted by Anna at April 17, 2016 - 1:21 PM

Slowly

Posted by Ashbur at April 29, 2016 - 1:23 PM

Study,
(function (n) {
alert(n);
})(3); Function add () is the prototype mean?

Posted by Frank at May 07, 2016 - 1:37 PM

var object={
function one() {},
function two() {}
}

Posted by Benedict at May 10, 2016 - 1:55 PM

Intuitively.

var a ="eeeee"
a.length

"eeeee".length//Error
("eeeee").length //The wood issue
function aa(){
alert(1)
}//I will execute him?
function aa(){
alert(1)
}()//???Error
(function aa(){
alert(i)
})()//The wood issue

In general "()" the expression computing

They see send. . .

Posted by Walker at May 22, 2016 - 2:52 PM

I understand the function add () said an anonymous function refers to the function inside
(3), The 3 argument and calls the anonymous function, inline style is equivalent to the following way, but direct eliminating the intermediate variables
var b1 = function (n) {
alert(n);
}
b1(3);
Declare the variable usage with C# in Action<T> use is the same, but the C# delegate temporarily does not support inline calls the delegate

Posted by Fred at May 23, 2016 - 3:13 PM

Finally, the code, the understanding of func1. Can appear the wrong answer, not because the closure, but not with the closure caused by. JS is a runtime binding. When the event handler is running, the external circulation would be over. So it is 4.

Posted by Alan at June 03, 2016 - 3:35 PM

Pass by, absorption

Posted by Tracy at June 16, 2016 - 4:30 PM

A bit dizzy, learning

Posted by Harrison at June 17, 2016 - 5:04 PM

(function($g){

function start1(a){} // Private methods
function start2(a){}
var count = 0; // Private variable
var a = {
start : function(){
count ++;
start1();
start2();
}
};

$g.a = a; // Up to $g, the only way to overseas visit

})(window);

I usually use it

Posted by Sandy at June 30, 2016 - 6:03 PM

In the c# example, this always point to the outer class, on the.?
For example

class A{
private A self = this;
public void a(){
object b = new Action(delegate(){
this.self == this; // Here this is the self, right
});
}
}

Posted by Sandy at July 01, 2016 - 6:46 PM

In learning

Posted by Toby at July 12, 2016 - 7:36 PM

Posted by Charlotte at July 16, 2016 - 7:46 PM





In learning

Posted by Randy at July 27, 2016 - 8:25 PM

The code also good collection

Posted by Christy at August 11, 2016 - 9:01 PM

Posted by Natalie at August 18, 2016 - 9:23 PM

<button id="btn">Button</button>
var btn = document.getElementById("btn");
for(var i=0; i<10; i++){
btn.onclick = function(i){
return function(){
alert(i)
}
}(i)
}
Now click the button is pop number 9,
I want every click to add 1 now;
That is to say the first click time is 1;
That is to say second times click is 2;
And so on...

Posted by Julian at August 27, 2016 - 9:36 PM

xue xi le

Posted by Devin at November 08, 2016 - 1:46 AM

23, who can help me to realize

Posted by Julian at November 13, 2016 - 1:47 AM

23, who can help me to realize

Posted by Becky at November 19, 2016 - 2:26 AM

document.write(results2[i]() + "<br/>");
Why this place is 10, for reasons

Posted by Roderick at November 21, 2016 - 3:22 AM

xuexixuexi

Posted by Bradley at December 01, 2016 - 3:54 AM

var btn = document.getElementById("btn");
btn.onclick = (function (v) {
return function () {
alert(v++);
};
})(1)

Posted by Daniel at December 09, 2016 - 4:01 AM

Many languages provide closure ability.

A closure, a very important point, the landlord is demonstrated with an example. But no basic law: closure are closed in the outside the variable itself, rather than the outside variables copy.
This means that, if the closure when the object in the A closure after the change (Javascript always to reference the way value), then the closure object in the A value has also changed.

In the cycle of the effect is really reflected, second as landlord to code in CreateArray2 and the twenty-third floor.
In order to eliminate the this effect, can use the landlord to the sample code in the CreateArray1 method

So, the 23 floor of a friend not read your posts.




By the way, about the closure, welcome to visit my blog articles about closures, Ruan Yifeng also wrote articles devoted to Javascript


Finally, note, the proper use of closure. Closure not correct will cause memory leaks, stack overflow problem.

Posted by Cliff at December 21, 2016 - 4:33 AM

The reply to 2011-10-24 10:13:04 was a moderator to delete

Posted by Jessie at January 02, 2017 - 5:17 AM

JS will package technology, why want to send to the.Net version.

Posted by Lance at January 11, 2017 - 6:04 AM

Learning to learn

Posted by Magee at January 12, 2017 - 6:32 AM

Posted by Byron at January 15, 2017 - 7:12 AM