Closures Explained

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

    #16
    Re: Closures Explained

    On Oct 11, 10:29 am, Dr J R Stockton <j...@merlyn.de mon.co.ukwrote:
    In comp.lang.javas cript message <be9b7575-f8f6-4c31-950e-9ef78d55626a@k3
    7g2000hsf.googl egroups.com>, Fri, 10 Oct 2008 10:06:52,
    MartinRineh...@ gmail.com posted:
    >
    >
    >
    >
    >
    David Mark wrote:
    "I had the best books (Flanagan, Resig, Crockford)"
    >
    Flanagan has been proven clueless and Resig's books belong in the
    comedy racks (or on a bonfire.)
    >
    And there isn't much there.  This is a far superior article:
    >>
    Flanagan is listed in the FAQ as the best JavaScript book.
    >
    The jibbering article is good. However, it's 10 times longer. My goal
    was to give some poor JavaScripter wannabe the basic idea so s/he
    could get on with writing code.
    >
    On matters concerning those who need mainly to learn the simple basics,
    there's little point in paying any attention to Lahn or Mark.  They may
    be right; but others will be more helpful.
    IIRC, Richard wrote the article in question. I think it is far more
    helpful than this new one, even for beginners. Certainly it is the
    first article on closures that I ever read and it really opened my
    eyes to the possibilities (and pitfalls.)

    Comment

    • John G Harris

      #17
      Re: Closures Explained

      On Sat, 11 Oct 2008 at 02:38:08, in comp.lang.javas cript, Thomas
      'PointedEars' Lahn wrote:

      <snip>
      >Incidentally , your definition of "JavaScript " as "the subset of ECMAScript
      >that Crockford defines in his book, JavaScript: The Good Parts." is useless
      >to those who have not already bought and read the book.
      <snip>

      Moreover, the language Crockford defines isn't JavaScript, or even
      javascript. It's a language where you aren't allowed to do

      ... { ... { ... } ... } ...

      but if you want to pervert Crockford's prejudices you are allowed to do

      ... { ... if (true) { ... } ... } ...

      instead.

      This is one of the reasons why I think links to the Crockford book
      should have a big warning label attached.

      John
      --
      John Harris

      Comment

      • Jorge

        #18
        Re: Closures Explained

        On Oct 10, 5:38 pm, MartinRineh...@ gmail.com wrote:
        I've rewritten a short article explaining closures in JavaScript.
        It's
         at:
        >

        >
        A big Thank You to PointedEars and Jorge for helping me get closer to
        the truth.
        Declare an outer function, including any necessary parameters and
        data. Declare an inner function. Have the outer function return the
        inner function.

        function outer([params]) {
        // vars declared here
        var closure = function([params]) { /* code here */ }

        return closure;
        }

        Or, manage somehow to keep a reference to the inner function, one that
        will last after the outer function has returned, as in:

        var refSaver;

        function outer([params]) {
        // vars declared here
        refSaver = function([params]) { /* code here */ }
        }

        Or:

        function outer([params]) {
        // vars declared here
        window.onresize = function([params]) { /* code here */ }
        }

        --
        Jorge.

        Comment

        • Jorge

          #19
          Re: Closures Explained

          On Oct 10, 5:38 pm, MartinRineh...@ gmail.com wrote:
          I've rewritten a short article explaining closures in JavaScript.
          It's
           at:
          >

          >
          A big Thank You to PointedEars and Jorge for helping me get closer to
          the truth.
          "The execution context contains names and values of, among others,
          variables, parameters and inner functions. When outer() returns a
          function it also returns its execution context at the time of the
          return."

          The idea is something like:

          0.- Upon entering a function, a new execution context is created for
          it.
          1.- The execution context of outer functions is accessible from within
          any inner functions.
          2.- When an outer function returns its current execution context is
          destroyed unless reference(s) to inner function(s) survive.
          3.- In that event, the execution context of the outer function can't
          be destroyed until all the references to inner functions that have
          access to it are destroyed as well.

          --
          Jorge.

          Comment

          • Jorge

            #20
            Re: Closures Explained

            On Oct 10, 5:38 pm, MartinRineh...@ gmail.com wrote:
            I've rewritten a short article explaining closures in JavaScript.
            It's
             at:
            >

            >
            A big Thank You to PointedEars and Jorge for helping me get closer to
            the truth.
            "Some authors said (and this was where I got confused) that the
            closure has access to the variables of the outer function. This is
            sort of true. Really it has access to the variable's names and values
            at the moment the closure is created."

            This isn't clear enough... a bit messy.

            An inner function that survives keeps working **exactly*as*it *did**
            before outer() returned. That's all. I'm not sure what do you mean
            with "Really it has access to the variable's names and values at the
            moment the closure is created" ? There's not any kind of 'memory
            effect' nor nothing like that...

            --
            Jorge.

            Comment

            • Lasse Reichstein Nielsen

              #21
              Re: Closures Explained

              Jorge <jorge@jorgecha morro.comwrites :
              On Oct 10, 5:38 pm, MartinRineh...@ gmail.com wrote:
              "Some authors said (and this was where I got confused) that the
              closure has access to the variables of the outer function. This is
              sort of true. Really it has access to the variable's names and values
              at the moment the closure is created."
              >
              This isn't clear enough... a bit messy.
              It's also wrong. The closure has access to the actual variables, not
              just their value at the time the closure was created, including any
              change to the variable, before or after the closure was created.T

              That's why the following doesn't work as most people expect it to:

              for (var i = 0; i < 10; i++) {
              setTimeout(func tion(){alert(i) ;},i*2000);
              }

              It alerts "10" all ten times.

              /L
              --
              Lasse Reichstein Holst Nielsen
              DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
              'Faith without judgement merely degrades the spirit divine.'

              Comment

              • Jorge

                #22
                Re: Closures Explained

                On Oct 10, 5:38 pm, MartinRineh...@ gmail.com wrote:
                I've rewritten a short article explaining closures in JavaScript.
                It's
                 at:
                >

                >
                "Really it has access to the variable's names and values
                at the moment the closure is created."

                No 'memory effects': in this example there are 10 different inner
                functions that survive after the outer (window.onload) function
                returns. They are created at different times and at different values
                of 'n'. But they all alert the same value: the value that n has in the
                (left orphan by window.onload's return) execution context of the outer
                function: 10.

                See: http://jorgechamorro.com/cljs/020/

                <script>
                window.onload= function () {
                var e, n;
                for (n=0; n<10; n++) {
                document.body.a ppendChild(
                e= document.create Element('button '
                )).innerHTML= n;
                e.onclick= function () { alert(n) };
                }
                };
                </script>

                --
                Jorge.

                Comment

                • Jorge

                  #23
                  Re: Closures Explained

                  On Oct 12, 12:13 am, Lasse Reichstein Nielsen <lrn.unr...@gma il.com>
                  wrote:
                  (...)
                  That's why the following doesn't work as most people expect it to:
                  >
                   for (var i = 0; i < 10; i++) {
                     setTimeout(func tion(){alert(i) ;},i*2000);
                   }
                  >
                  It alerts "10" all ten times.

                  On Oct 12, 12:17 am, Jorge <jo...@jorgecha morro.comwrote:
                  >
                  (..) But they all alert the same value: the value that n has in the
                  (left orphan by window.onload's return) execution context of the outer
                  function: 10.
                  >
                  LOL :-)

                  --
                  Jorge.

                  Comment

                  • Dr J R Stockton

                    #24
                    Re: Closures Explained

                    In comp.lang.javas cript message <gcov6t$hcv$1@r egistered.motza rella.org>
                    , Fri, 10 Oct 2008 18:23:40, dhtml <dhtmlkitchen@g mail.composted:
                    >D. Flanagan himself has said that the Pocket Reference was "probably
                    >out of date."
                    >http://groups.google.com/group/comp....866b23771e3a75
                    >e?dmode=sour ce
                    Any book user or buyer should check its publication date (the publisher
                    and the year should be added to the FAQ entries), and not expect it to
                    cover anything more recent.

                    Since most JavaScript is executed by an agent remote from the author, by
                    various browsers of various ages, an Internet author should be very wary
                    of using anything that is not in ISO/IEC 16262.

                    Pocket Flanagan 2, October 2002, should cover what is in ECMA 262.

                    For those Flanagans, the FAQ should link to index.html not toc.html;
                    index should link to toc.

                    --
                    (c) John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v6.05 MIME.
                    Web <URL:http://www.merlyn.demo n.co.uk/- FAQish topics, acronyms, & links.
                    Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
                    Do not Mail News to me. Before a reply, quote with ">" or "" (SonOfRFC1036)

                    Comment

                    • Peter Michaux

                      #25
                      Re: Closures Explained

                      On Oct 10, 8:44 am, David Mark <dmark.cins...@ gmail.comwrote:
                      On Oct 10, 11:38 am, MartinRineh...@ gmail.com wrote:
                      >
                      I've rewritten a short article explaining closures in JavaScript.
                      It's
                       at:
                      >>
                      It gets off to a dubious start:
                      >
                      "I had the best books (Flanagan, Resig, Crockford)"
                      >
                      Flanagan has been proven clueless
                      I think "clueless" is incorrect and inappropriate. He knows a lot as
                      displayed many times in his book and I still find his book a useful
                      starting resource for most browser-related issues. Yes his book has
                      mistakes but that does not make him clueless.

                      Peter

                      Comment

                      • Peter Michaux

                        #26
                        Re: Closures Explained

                        On Oct 10, 10:06 am, MartinRineh...@ gmail.com wrote:
                        David Mark wrote:
                        "I had the best books (Flanagan, Resig, Crockford)"
                        >
                        Flanagan has been proven clueless and Resig's books belong in the
                        comedy racks (or on a bonfire.)
                        >
                        And there isn't much there.  This is a far superior article:
                        >>
                        Flanagan is listed in the FAQ as the best JavaScript book.
                        "best" is a comparative term.

                        The jibbering article is a good resource.

                        Peter

                        Comment

                        • Conrad Lender

                          #27
                          Re: Closures Explained

                          On 2008-10-12 19:49, John G Harris wrote:
                          >>Moreover, the language Crockford defines isn't JavaScript, or even
                          >>javascript. It's a language where you aren't allowed to do
                          >>>
                          >>... { ... { ... } ... } ...
                          >>
                          >>Where does he say that?
                          >
                          In the syntax diagrams.
                          OK, I see what you mean. This is on the same page where he writes that
                          "if(expression) " can only be followed by a block. The grammar he's
                          defining here is not that of javascript, but of the subset he calls the
                          Good Parts. That's the whole point of the book - dividing the language
                          into good and bad (and, in the appendix, awful) parts. I think most
                          people who work with any language for a while instinctively do the same
                          thing in their minds, and Crockford wrote a book about it. As I said,
                          it's not a tutorial, but a collection of opinions.
                          I don't think he says in words that he doesn't want to nest blocks.
                          Perhaps he couldn't think of any way of discouraging people from doing
                          >
                          ... { ... if (true) { ... } ... } ...
                          Off the top of my head I can't think of a single reason to use a block
                          unless it's necessary (except following if/else/for/while/etc, which is
                          a question of coding style) so I think that excluding them from the Good
                          Parts was the correct choice. "if (true) {...}" doesn't make any sense
                          at all.
                          For the record, I do disagree on quite a number of other suggestions and
                          opinions in the book, but that hardly made it worthless for me.


                          - Conrad

                          Comment

                          • David Mark

                            #28
                            Re: Closures Explained

                            On Oct 12, 2:41 pm, Peter Michaux <petermich...@g mail.comwrote:
                            On Oct 10, 8:44 am, David Mark <dmark.cins...@ gmail.comwrote:
                            >
                            On Oct 10, 11:38 am, MartinRineh...@ gmail.com wrote:
                            >
                            I've rewritten a short article explaining closures in JavaScript.
                            It's
                             at:
                            >>
                            It gets off to a dubious start:
                            >
                            "I had the best books (Flanagan, Resig, Crockford)"
                            >
                            Flanagan has been proven clueless
                            >
                            I think "clueless" is incorrect and inappropriate. He knows a lot as
                            His name has come up here a lot over the years. It seems to me that
                            most of it was bad. I certainly wouldn't recommend buying his books.
                            He's no Resig when it comes to cluelessness. I'll leave it at that.

                            Comment

                            • Peter Michaux

                              #29
                              Re: Closures Explained

                              On Oct 12, 7:15 pm, David Mark <dmark.cins...@ gmail.comwrote:
                              On Oct 12, 2:41 pm, Peter Michaux <petermich...@g mail.comwrote:
                              >
                              >
                              >
                              On Oct 10, 8:44 am, David Mark <dmark.cins...@ gmail.comwrote:
                              >
                              On Oct 10, 11:38 am, MartinRineh...@ gmail.com wrote:
                              >
                              I've rewritten a short article explaining closures in JavaScript.
                              It's
                               at:
                              >>
                              It gets off to a dubious start:
                              >
                              "I had the best books (Flanagan, Resig, Crockford)"
                              >
                              Flanagan has been proven clueless
                              >
                              I think "clueless" is incorrect and inappropriate. He knows a lot as
                              >
                              His name has come up here a lot over the years.  It seems to me that
                              most of it was bad.
                              People seem to like to point out the mistakes because that is actually
                              useful. It would be boring and pointless to read about all the he
                              wrote that are correct.

                              I certainly wouldn't recommend buying his books.
                              That is a different story. I would recommend his book but would warn
                              that there are errors both small and large. I think a beginner is best
                              served by a paper book that covers the language and the DOM.
                              Flanagan's book fits that bill best of the options available. It isn't
                              so good to say to a beginner, "hey there are some documents on there
                              and there on the web. Try the terse specs and the Mozilla site and the
                              archives of c.l.js are good but there is a lot of pedantic arguing to
                              wade through. Just jump in the deep end with the sharks." Flangan's
                              book is a much more gentle introduction.

                              Peter

                              Comment

                              • sasuke

                                #30
                                Re: Closures Explained

                                On Oct 10, 9:07 pm, Lasse Reichstein Nielsen <lrn.unr...@gma il.com>
                                wrote:
                                >
                                [snip]
                                >
                                A closure is a piece of code together with a binding of values to the
                                free variables of that code.
                                >
                                A free variable is one that occur in the code, but is not declared
                                there.
                                So does it mean that even global variables in Javascript are `free
                                variables' given the fact that they can be used without being declared
                                or is it that the definition is a loose one?

                                Also, given the function:

                                ---------------------------------->B--------------------------
                                function attachEvents() {
                                var divs = document.getEle mentsByTagName( "DIV");
                                if(!divs) return;
                                for(var i = 0, maxI = divs.length; i < maxI; ++i) {
                                var d = divs[i];
                                d.onclick = function() {
                                // some complicated processing with a lot of variables
                                alert("Hello from " + d.id);
                                }
                                }
                                }
                                window.onload = function() {
                                attachEvents();
                                // something complicated
                                attachEvents();
                                }
                                ---------------------------------->B--------------------------

                                Will the second invocation of the function `attachEvents' make the
                                execution context of the first run along with the previously created
                                function objects eligible for garbage collection or do they need to be
                                explicitly grounded [set to null]?

                                /sasuke

                                Comment

                                Working...