Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #16145

Re: Anonymous function in closure

Newsgroups comp.lang.javascript
Date 2012-09-24 15:18 -0700
References <8ZOdnd6tG7eeAcLNnZ2dnUVZ_vGdnZ2d@westnet.com.au>
Message-ID <6e448087-cdec-4edd-ada8-21def1f2c0bf@googlegroups.com> (permalink)
Subject Re: Anonymous function in closure
From webnician@gmail.com

Show all headers | View raw


function foo(a) { 
   return function() { 
     // do something with a 
   }; 
} 

var bar = foo(10); 

- - - - - - - - - - - - - - -

The value of 'a' is not passed to the function 'bar', rather it becomes part of its environment, as if it was outside, in the global scope. The beauty of a closure is that you have a flexible way to 'construct' another function. The important trick is...
1) 'a' will persist for each call of bar() as if it was in the global scope
2) 'a' is not actually in the global scope to cause conflicts


A simple example...

function Plus(x) {
    return function (y) {
        return y + x;
    }
}

var plus8 = Plus(8);
var plus3 = Plus(3);

plus8(10); --> 18
plus8(3); --> 11
plus3(1); --> 4


- - - - - - - - - - - - - - -

A better example...

function Count() {
    var x = 0;
    return function() {
        x += 1;
        return x;
    }
}

var countA = Count();
var countB = Count();


countA(); --> 1
countA(); --> 2
countA(); --> 3
countB(); --> 1
countB(); --> 2
countA(); --> 4

Back to comp.lang.javascript | Previous | Next — Previous in thread | Find similar | Unroll thread


Thread

Anonymous function in closure Andrew Poulos <ap_prog@hotmail.com> - 2012-09-24 09:32 +1000
  Re: Anonymous function in closure David Mark <dmark.cinsoft@gmail.com> - 2012-09-23 17:09 -0700
    Re: Anonymous function in closure Andrew Poulos <ap_prog@hotmail.com> - 2012-09-24 14:20 +1000
      Re: Anonymous function in closure David Mark <dmark.cinsoft@gmail.com> - 2012-09-24 00:10 -0700
      Re: Anonymous function in closure Gene Wirchenko <genew@ocis.net> - 2012-09-24 11:09 -0700
        Re: Anonymous function in closure Gene Wirchenko <genew@ocis.net> - 2012-09-24 13:27 -0700
  Re: Anonymous function in closure webnician@gmail.com - 2012-09-24 15:18 -0700

csiph-web