Function return function???

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • strout

    #1

    Function return function???

    function F(e)
    {
    return
    function(){P(e) }
    }

    Can anybody tell me what the code is doing?

    If return another function all in a function I would do
    function F(e)
    {
    return P(e)
    }

    Is it defining another function? I don't recall other languages can
    define another function inside one function. Why would the programmer
    do this?

  • Jarmo

    #2
    Re: Function return function???

    "strout" <zjjiang@hotmai l.com> wrote in message
    news:1109273953 .202236.117440@ o13g2000cwo.goo glegroups.com.. .[color=blue]
    >
    > If return another function all in a function I would do
    > function F(e)
    > {
    > return P(e)
    > }[/color]

    That returns the *result* of calling the function P(e).


    Comment

    • strout

      #3
      Re: Function return function???

      what i am trying to ask is what's this code doing

      function F(e)
      {
      return
      function(){P(e) }
      }

      Comment

      • Jarmo

        #4
        Re: Function return function???

        "strout" <zjjiang@hotmai l.com> wrote in message
        news:1109277112 .046355.267090@ z14g2000cwz.goo glegroups.com.. .[color=blue]
        > what i am trying to ask is what's this code doing
        >
        > function F(e)
        > {
        > return
        > function(){P(e) }
        > }[/color]

        To do unspeakable things that no-one will ever be able to support ;-)


        Find information, resources and relevant links for svendtofte.com. This domain may be for sale.



        Comment

        • strout

          #5
          Re: Function return function???

          Well, it's from Gmail Javascript file. Gmail is generated by pure
          javascript from backend.

          Guess I have to write some code to figure it out myself.

          Comment

          • Lee

            #6
            Re: Function return function???

            strout said:[color=blue]
            >
            >what i am trying to ask is what's this code doing
            >
            >function F(e)
            >{
            >return
            >function(){P(e )}
            >}[/color]

            It creates a new function and returns it.


            document.getEle mentById("alpha ").onclick=F(11 78);

            Clicking on alpha will now execute P(1178)

            Comment

            • strout

              #7
              Re: Function return function???

              So you will have to declare P something like

              function P(e)
              {
              alert(e);
              }

              So basically it's same as
              document.getEle mentById("alpha ").onclick=P(11 78);

              What's the catch here?

              Comment

              • Yann-Erwan Perio

                #8
                Re: Function return function???

                Jarmo wrote:

                [closures]
                [color=blue]
                > To do unspeakable things that no-one will ever be able to support ;-)[/color]

                Then spread the damn thing so that every professional be aware of it and
                use it everywhere; javascript's real power lies hidden in closures:-)

                While it'd be true that the concept and resulting code may look obscure
                to programmers unfamiliar with the functional paradigm, closures still
                remain fully supported by javascript and IMHO offer programmers willing
                to use them (that is, using the js paradigm to its full potential),
                quite a formidable asset in large apps designing.

                Of course you're right, most js programmers have never heard about the
                techniques and keep using "simple" javascript - however would you trust
                maintainers unable to understand properly-documented closures-based code
                to be skilled enough to offer anyway an acceptable level of quality in
                application maintenance?


                Cheers,
                Yep 'closures aren't that hard'.

                Comment

                • Yann-Erwan Perio

                  #9
                  Re: Function return function???

                  strout wrote:
                  [color=blue]
                  > So basically it's same as
                  > document.getEle mentById("alpha ").onclick=P(11 78);[/color]

                  It's not the same, in Lee's example the function returns a function,
                  your example doesn't return anything but undefined. When the click event
                  is dispatched you'll have no handler to capture it.
                  [color=blue]
                  > What's the catch here?[/color]

                  The basic thing is that the inner function can access the outer function
                  local variables, even after the outer function has returned the inner
                  function. This permits to build private/public scopes, see the articles
                  that Jarmo has advised if you want to dig the matter further.


                  Regards,
                  Yep.

                  Comment

                  • Michael Winter

                    #10
                    Re: Function return function???

                    strout wrote:
                    [color=blue]
                    > function F(e)
                    > {
                    > return
                    > function(){P(e) }
                    > }
                    >
                    > Can anybody tell me what the code is doing?[/color]

                    As is, nothing. It is a breach of the grammar rules for a return
                    statement to be followed by a line terminator. The code would be
                    parsed as:

                    function F(e) {
                    return;
                    function() {P(e);};
                    }

                    Notice the added statement-terminating semicolons. The function
                    expression would never be evaluated.

                    Pedantry aside, it does what you think it does: creates a function
                    object via a function expression and returns that object. However, the
                    nature of the creation of that object is special. Namely, the value of
                    e passed to F will be passed to P any time the returned function is
                    called. Consider:

                    function A(n) {
                    return function() {alert(n);};
                    }

                    var B = A(1),
                    C = A(2);

                    The variables B and C now contain references to function object
                    created by the call to A. No matter when B or C is called, the former
                    will display 1 and the latter, 2. This is true even the initial calls
                    to A have returned and (you might have thought) the value of n is of
                    no relevance. If you care to read the cited explanations, you'll see
                    that in fact the value of n does continue to exist in the execution
                    context of B and C, allowing them to refer to, and display, those values.

                    [snip]

                    Hope that helps,
                    Mike

                    --
                    Michael Winter
                    Replace ".invalid" with ".uk" to reply by e-mail.

                    Comment

                    • Jarmo

                      #11
                      Re: Function return function???

                      "Yann-Erwan Perio" <y-e.perio@em-lyon.com> wrote in message
                      news:421e4c2d$0 $2553$626a14ce@ news.free.fr...[color=blue]
                      > Jarmo wrote:
                      >
                      > [closures]
                      >[color=green]
                      > > To do unspeakable things that no-one will ever be able to support ;-)[/color]
                      >
                      > Then spread the damn thing so that every professional be aware of it and
                      > use it everywhere; javascript's real power lies hidden in closures:-)[/color]

                      I've yet to see a compelling need for closures in JavaScript but I'm open to
                      suggestion. Bring it on ;-)

                      Personally, I'd have preferred them to have designed variable scoping
                      correctly and at least provided an option for strong types then I'd have a
                      lot more enthusiasm for the more esoteric features.


                      Comment

                      • Anthony Borla

                        #12
                        Re: Function return function???


                        "Yann-Erwan Perio" <y-e.perio@em-lyon.com> wrote in message
                        news:421e4c2d$0 $2553$626a14ce@ news.free.fr...[color=blue]
                        > Jarmo wrote:
                        >
                        > [closures]
                        >[color=green]
                        > > To do unspeakable things that no-one will ever be able
                        > > to support ;-)[/color]
                        >
                        > Then spread the damn thing so that every professional be
                        > aware of it and use it everywhere; javascript's real power
                        > lies hidden in closures:-)
                        >[/color]

                        I suppose another way to achieve this is to paste links to Douglas
                        Crockford's site *everywhere* ;) !
                        [color=blue]
                        >
                        > While it'd be true that the concept and resulting code may
                        > look obscure to programmers unfamiliar with the functional
                        > paradigm, closures still remain fully supported by javascript
                        > and IMHO offer programmers willing to use them (that is,
                        > using the js paradigm to its full potential), quite a formidable
                        > asset in large apps designing.
                        >[/color]

                        It's a pity so many developers out there do not learn such techiques. Even
                        if not used in day-to-day developemnt, they would at least offer a developer
                        an addeded insight into the development process. It seems to me, however,
                        that unless a developer completes a Scheme-based course in high school or
                        college [let's be honest: what professional developer would shell out $$$ to
                        enrol in such a course], then the chances of learning about closures, or
                        other metaprogramming techniques, is marginally greater than zero.

                        What's also a pity is that there is obviously room for the use of these more
                        advanaced techniques, but the mechanisms by which they are supported in
                        popular developer languages are either overly complex [think C++ templates]
                        or cumbersome to use [think Java reflection; introspection in Python etc].
                        Yet, rather than looking at alternatives, developers struggle with these
                        problems, and assume that development *should* be a such struggle.
                        [color=blue]
                        >
                        > Of course you're right, most js programmers have never
                        > heard about the techniques and keep using "simple" javascript
                        > - however would you trust maintainers unable to understand
                        > properly-documented closures-based code to be skilled
                        > enough to offer anyway an acceptable level of quality in
                        > application maintenance?
                        >[/color]

                        The irony is that such power is present in what is so, all-too-commonly,
                        regarded as a 'toy' language. And that it [JavaScript] has been so-marketed
                        is one of those sad accidents of history.

                        Still, it seems to me that hope for JavaScript to become more than a browser
                        client language seems to be with any efforts to produce bytecode compilers.
                        Perhaps standardised versions targeting the .NET or JVM platforms, together
                        with beefed up host access capabilities [e.g. better access to system
                        services] ?
                        [color=blue]
                        >
                        > Cheers,
                        > Yep 'closures aren't that hard'.
                        >[/color]

                        And the even greater irony is that closures have been around since around
                        the 1960's with LISP [no wonder many LISPer's often come across as smug and
                        superior - they've had all this 'power' at their disposal for so long ;) !]

                        Cheers,

                        Anthony Borla


                        Comment

                        • Anthony Borla

                          #13
                          Re: Function return function???

                          "strout" <zjjiang@hotmai l.com> wrote in message
                          news:1109280161 .550984.279040@ z14g2000cwz.goo glegroups.com.. .[color=blue]
                          > Well, it's from Gmail Javascript file. Gmail is generated by pure
                          > javascript from backend.
                          >
                          > Guess I have to write some code to figure it out myself.
                          >[/color]

                          I find writing up quick 'code doodles' to be the key to understanding code,
                          thereby gaining insight into new / unknown techniques.

                          Some such doodles below - adjust to suit.

                          Cheers,

                          Anthony Borla

                          // --------- Function Doodles -----------

                          // Using WSH as host

                          function newline()
                          {
                          WScript.Echo();
                          }

                          function showMeta(name, arg)
                          {
                          WScript.Echo("I tem " + name + " metadata:");
                          WScript.Echo("V alue -> |" + arg + "|");
                          WScript.Echo("T ype -> |" + typeof arg + "|");
                          }

                          function F1(e)
                          {
                          // Implicit return of undefined
                          }

                          function F2(e)
                          {
                          // Value of of argument 'e' returned
                          return e;
                          }

                          function F3()
                          {
                          // Return of function 'G' definition [note:
                          // name not really needed]
                          return function G(e) { return e * 2; };
                          }

                          function F4(e)
                          {
                          // Return of function 'G' application [note:
                          // name not really needed]
                          return function G(f) { return 2 * f; }(e);
                          }

                          var r, r1;

                          // Call functions:

                          // 'F1' arg = 5, return value = undefined
                          r = F1(5);
                          showMeta("F1:r" , r);


                          // 'F2' arg = 5, return value = 5
                          r = F2(5);
                          newline(); showMeta("F2:r" , r);


                          // 'F3' arg = N/A, return value = function
                          // 'r1' arg = 5, return value = 10 [application
                          // of returned function]

                          r = F3();
                          newline(); showMeta("F3:r" , r);

                          r1 = r(5);
                          newline(); showMeta("F3:r1 ", r1);


                          // 'F4' arg = 5, return value = 10 [application
                          // of function]
                          r = F4(5);
                          newline(); showMeta("F4:r" , r);


                          Comment

                          • strout

                            #14
                            Re: Function return function???

                            Thanks.
                            I don't have much programming experience but I do have taken full
                            cirriculmn in CS. This is my first time read about 'closure'.

                            I am wondering what it takes to be able to write complex code, for
                            example, the one I found from Google's Gmail. I always though
                            Javascript is easy until I begin to study Google's JS file. Most of my
                            time I use Microsoft IDE. C# and VB.net. I think it's great because you
                            can put more time on thinking and analysis work flow. IDE is taking
                            take of many things for you.

                            I don't know if it's a good trend or not. Programmers become more
                            productive? or maybe not.

                            :(

                            strout

                            Comment

                            • RobG

                              #15
                              Re: Function return function???

                              Jarmo wrote:
                              [...][color=blue]
                              > I've yet to see a compelling need for closures in JavaScript but I'm open to
                              > suggestion. Bring it on ;-)
                              >
                              > Personally, I'd have preferred them to have designed variable scoping
                              > correctly and at least provided an option for strong types then I'd have a
                              > lot more enthusiasm for the more esoteric features.[/color]

                              I'm a newbie to JavaScript, but find it a fascinating language.
                              Your request for a compelling reason for closures and subsequent
                              comment on scoping and types can be take two ways:

                              1. There is no need to have closures or similar functionality

                              2. There are other (presumably better) ways to achieve the same
                              functionality

                              I certainly can't comment on the second point, but an argument
                              for the first is where you want to call a function using say
                              setInterval and want to pass a lot of parameters. You can
                              create an "outer" function that does all the setup work and
                              creates any required variables, then use setInterval to call an
                              "internal" function that uses the variables.

                              The internal function has access to all the variables created in
                              the outer function, but you haven't needed to pass them and
                              their cope does not need to be global. You can keep the
                              internal processing tight and fast 'cos all the heavy work was
                              done beforehand.


                              --
                              Rob

                              Comment

                              Working...