Closures in JS and closures in C #

Source: Internet
Author: User

We

About closures, a old monk talk of the topic, JS closure I will be more, and very detailed, I will not say, you can look at the previous article;

Let's compare the closures in C # and the closure in JS;

Look at our C # code first;

        StaticList<action>fn0 () {intresult =0; List<Action> list =NewList<action>();  for(inti =0; I <Ten; i++) {result= i +1;//This result is equivalent to a global variableAction action = () ={Console.WriteLine (result);                }; List.            ADD (action); }            returnlist; }        StaticList<action>fn1 () {List<Action> list =NewList<action>();  for(inti =0; I <Ten; i++)            {               intresult = i +1;//this is equivalent to a local variable; A variable inside a for loop;Action action = () ={Console.WriteLine (result);                }; List.            ADD (action); }            returnlist; }        Static voidMain (string[] args) {            //so see, the results of all Nima is ten drops ah;Fn0 (). ForEach (o=>o ()); Console.WriteLine ("------------------");//The problem of closures will appear in our For loop and multi-threaded ID AH;FN1 (). ForEach (o =o ()); }

The results are conceivable;

So for the second way, if we use the JS code to implement it, (Ps:js array can directly save our function, Ps:js function is the object, so you can save)

function Show () {  var arr=[];  for (var i=0;i<10;i++) {      var result=i+1;     Arr.push (function  () {         console.log (result);             })        }   return arr;}; var list=Show ();

for (Var i=0;i<list.length;i++) {
List[i] ();
}

Results:

The reason for this is very simple, I do not want to repeat, because there is no block-level scope of the concept of JS, no no no, this is not correct, the specific should be in the ESX version before, the specific I also remember not clear;

There are many ways to solve the problem, to form closures, to use the Let keyword.

Let's take a look at how closures are formed;

functionShow () {varArr=[]; for(vari=0;i<10;i++){      varResult=i+1; Arr.push (function(index) {return function() {console.log (index); }} (Result)}returnarr;};varlist=Show (); for(vari=0;i<list.length;i++) {list[i] ();}

It uses our function (the outermost function) to form a new scope (RESULT=INDEX), so that the I=>result=>index is formed, and one of our independent block levels is used for dropping.

The method is quite ingenious, but for the new ES, a let can solve the problem;

Summary: The nature of the problem: JS does not have block level scope, through function to form a new level of scale scope, so that innerfunction access to outerfunction variables (parameters), the formation of our closure;

One of the definitions of closures: Here I emphasize one of the definitions://functions within the scope of the function can be accessed, of course, it has an obvious problem is: memory leaks;


Looking back at our code in C #, there is a block-level scope in C #, so there is no problem with method two;

Let's look at the Wikipedia definition:

Closures: lexical closures; a function that refers to a free variable; the quoted free variable, which exists with this function, is already out of the environment that created it; There is another way of saying that:

Closures are entities that are composed of functions and their associated reference environments;

var 1  = () =var2var result = x + y; Console.Out.WriteLine ("result = {0}", result);}; Action ();

When you look at "action" in the Code debugger (debugger), you'll find something interesting. As we can see, the C # compiler created a Target class for us that encapsulates the X variable:

As the topmost pest, we call it in the Fn0 (for the first result), except that the variable is still present; This is where we are angry about the closure;

How to avoid closure traps? A common practice in C # is to save the variable referenced by an anonymous function with a temporary variable and then use the temporary variable in the anonymous function

Let's look at a classic JS code:

function Show () {      var n=12;     return function () {n+ +;          Console.log (n);    }} var fuck=Show (); fuck (); fuck (); fuck () ;

Results:

Key point: loop nested reference;

The same Code C # how to implement it;

 public  class   person { public   Action show () { var  n = 12  ;  return  () => {N++;                           Console.WriteLine (n);        };  }} public class program{
static void Mian (string [] args) {person P = new person (); var fuck = P.show (); Fuck (); Fuck (); Fuck ();
}
}

Results:

From the above code, it is not difficult to see that the variable n is actually a local variable belonging to the function T1, it would have been freed from the end of the call of the function T1, but here we can still invoke it in the returned delegate B.

Closures in JS and closures in C #

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.