Closures Explained

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • MartinRinehart@gmail.com

    Closures Explained

    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.
  • David Mark

    #2
    Re: Closures Explained

    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 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:


    Comment

    • Lasse Reichstein Nielsen

      #3
      Re: Closures Explained

      MartinRinehart@ gmail.com writes:
      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.
      Comments:

      In the example:
      function outer() {
      // args here
      // code here
      function inner() {
      // more args and code
      }
      } // end of outer()
      the "args here" comment seems slightly misleading. Arguments goes
      between the parentheses. Maybe use:
      function outer(/* arguments here *) {
      instead.

      The sentence "A closure is a bundle of data and code that manipulates
      that data" is still indistinguishab le from the description of an
      Object.

      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.

      The next sentence, "In JavaScript it's a function with data that's
      unavailable, except to the function." is closer, but also wrong.
      The data, and even the bindings, might be available to other code too.

      Example:

      function pair(a,b) {
      return {setFst : function(x){a=x ;},
      setSnd : function(x){b=x ;},
      sum : function() { return a+b; }};
      }

      var p = pair(2,4);
      var s = p.sum; // s holds a clousre, but its data and bindings
      // are available through, e.g., pair.setFst:
      alert(s());
      p.setFst(38);
      alert(s());

      So, what you describe as "What is a Closure?" isn't correct. It is
      one use of a closure: to create functions with shared private variables.
      It seems this use of closures is the focus of your page, but it should
      really be named "private variables in Javascript, using closures" instead.

      Closures are MUCH more than just that, e.g.:

      function curry(f) {
      return function(a) {
      return function (b) {
      return f(a,b);
      }
      }
      }
      function sum(a,b) { return a+b;};
      var csum = curry(sum);
      var inc = csum(1);
      var addFive = csum(5);
      alert([inc(41),addFive (37)]);


      or it can be used to express something complicated in a simpler way:

      function map(arr,f) {
      var res = [];
      for(var i = 0; i < arr.length; i++) {
      res[i] = f(arr[i]);
      }
      return res;
      }

      function cross(arr1,arr2 ) {
      return map(arr1, function(x1) {
      return map(arr2, function(x2) { return [x1,x2]; });
      });
      }

      var pair_matrix = cross([1,2,3],[4,5,6]);
      // pair_matrix ==
      // [[[1,4],[1,5],[1,6]],
      // [[2,4],[2,5],[2,6]],
      // [[3,4],[3,5],[3,6]]]

      (try doing it shorter using nested loops :)

      And to prettify it:

      alert(map(pair_ matrix, function(a1) {
      return map(a1, function(a2) {
      return "(" + a2[0] + "," + a2[1] +")";
      }).join(",");
      }).join("\n"));

      To put it bluntly: Closures allow you to write functional programs.
      If only we had tail-calls, it would be perfect :)

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

      Comment

      • MartinRinehart@gmail.com

        #4
        Re: Closures Explained



        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:
        >
        http://www.jibbering.com/faq/faq_notes/closures.html
        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.

        Comment

        • MartinRinehart@gmail.com

          #5
          Re: Closures Explained

          On Oct 10, 12:07 pm, Lasse Reichstein Nielsen <lrn.unr...@gma il.com>
          wrote:
          the "args here" comment seems slightly misleading.
          ... between the parentheses. Maybe use:
          Stupid me. That's 'vars'. Double dumb: the rewrite was on my computer,
          not ULd. Fixed that, too.

          I'll go through the rest of your points when I've got the time they
          seem to deserve. Thanks.

          Comment

          • David Mark

            #6
            Re: Closures Explained

            On Oct 10, 1:06 pm, 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.
            >
            I thought it was listed as the lesser evil. It is not an endorsement.

            Comment

            • dhtml

              #7
              Re: Closures Explained

              David Mark wrote:
              On Oct 10, 1:06 pm, 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:
              >>http://www.jibbering.com/faq/faq_notes/closures.html
              >Flanagan is listed in the FAQ as the best JavaScript book.
              >>
              >
              I thought it was listed as the lesser evil. It is not an endorsement.


              | Although many books have been reviewed, most are quite bad and cannot
              | be recommended.
              |
              | The following list of books been approved by CLJ regulars after
              | critical review.
              |
              ....

              Garrett

              Comment

              • Jorge

                #8
                Re: Closures Explained

                On Oct 10, 5:44 pm, David Mark <dmark.cins...@ gmail.comwrote:
                >
                It gets off to a dubious start:
                >
                "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.)

                A doubt a book by you or Mr. Speck would be better nor more
                understandable nor more comprehensible. And sure you the Mr. I'm
                perfect clan have your own dose of JS misunderstandin gs as well...
                Nobody is perfect, no, not even Mr. Flanagan.

                But because there are a couple of things or three that aren't 100%
                perfect in 994 pages it doesn't mean that overall it's not an
                excellent book.
                Excellent means well above others, first-class. It's excellent.

                --
                Jorge.

                Comment

                • David Mark

                  #9
                  Re: Closures Explained

                  On Oct 10, 5:33 pm, Jorge <jo...@jorgecha morro.comwrote:
                  On Oct 10, 5:44 pm, David Mark <dmark.cins...@ gmail.comwrote:
                  >
                  >
                  >
                  It gets off to a dubious start:
                  >
                  "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.)
                  >
                  A doubt a book by you or Mr. Speck would be better nor more
                  Me or who?
                  understandable nor more comprehensible. And sure you the Mr. I'm
                  What do you know about some hypothetical book?
                  perfect clan have your own dose of JS misunderstandin gs as well...
                  Nobody is perfect, no, not even Mr. Flanagan.
                  Where are you going with this?
                  >
                  But because there are a couple of things or three that aren't 100%
                  perfect in 994 pages it doesn't mean that overall it's not an
                  excellent book.
                  Excellent means well above others, first-class. It's excellent.
                  Which "it" are you even talking about? AFAIK, they are all a waste of
                  money.

                  Comment

                  • Thomas 'PointedEars' Lahn

                    #10
                    Re: Closures Explained

                    dhtml wrote:
                    David Mark wrote:
                    >On Oct 10, 1:06 pm, 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:
                    >>>http://www.jibbering.com/faq/faq_notes/closures.html
                    >>Flanagan is listed in the FAQ as the best JavaScript book.
                    >>
                    >I thought it was listed as the lesser evil. It is not an endorsement.
                    >
                    http://jibbering.com/faq/#onlineResources
                    You meant <http://jibbering.com/faq/#books>.
                    | Although many books have been reviewed, most are quite bad and cannot
                    | be recommended.
                    |
                    | The following list of books been approved
                    A "has" was missing if the statement was correct in the first place.
                    by CLJ regulars after critical review.
                    ^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^
                    Double nonsense.


                    PointedEars
                    --
                    Use any version of Microsoft Frontpage to create your site.
                    (This won't prevent people from viewing your source, but no one
                    will want to steal it.)
                    -- from <http://www.vortex-webdesign.com/help/hidesource.htm>

                    Comment

                    • RobG

                      #11
                      Re: Closures Explained

                      On Oct 11, 6:33 am, dhtml <dhtmlkitc...@g mail.comwrote:
                      David Mark wrote:
                      On Oct 10, 1:06 pm, MartinRineh...@ gmail.com wrote:
                      David Mark wrote:
                      [...]
                      >And there isn't much there.  This is a far superior article:
                      >>http://www.jibbering.com/faq/faq_notes/closures.html
                      Flanagan is listed in the FAQ as the best JavaScript book.
                      >
                      I thought it was listed as the lesser evil. It is not an endorsement.
                      >

                      >
                      |  Although many books have been reviewed, most are quite bad and cannot
                      | be recommended.
                      |
                      | The following list of books been approved by CLJ regulars after
                      | critical review.
                      I would not include the phrase "after critical review", which infers
                      that a number of CLJ regulars have read it cover-to-cover and
                      commented on or approved all the facts presented. I don't recall
                      anyone here claiming to have done that, much less a sufficient number
                      of regulars for the statement to be true.

                      The book presents a number of topics outside the focus of this group
                      related to HTML, CSS, XML and others - there's even a section on E4X.
                      I don't recall anyone commenting on those sections, nor are those
                      topics regularly discussed here in any depth.

                      The general opinion (not held by everyone, but most I think) is that
                      it is the best of a bad lot. That sentiment should be maintained in
                      the text of the FAQ.


                      --
                      Rob

                      Comment

                      • Thomas 'PointedEars' Lahn

                        #12
                        Re: Closures Explained

                        MartinRinehart@ gmail.com wrote:
                        I've rewritten a short article explaining closures in JavaScript.
                        It's at:
                        >
                        http://www.martinrinehart.com/articl...-closures.html
                        | Unlike most JavaScript attributes (remember: all JavaScript variables are
                        | attributes)

                        "JavaScript ", as understood in your article, has objects (e.g. Function
                        objects). Objects may have *properties* (e.g. `length'). Properties
                        (internally) may have attributes (e.g. `DontDelete').

                        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.

                        And that were but the two paragraphs I am currently able to look into.
                        A big Thank You to PointedEars and Jorge for helping me get closer to
                        the truth.
                        You are welcome, although I think that you still have a long way to go and
                        will likely end up with what is in the FAQ, FAQ Notes, and newsgroup
                        archives. Especially, before trying to explain a complex concept such as
                        closures, you should get the basics right.


                        PointedEars
                        --
                        Anyone who slaps a 'this page is best viewed with Browser X' label on
                        a Web page appears to be yearning for the bad old days, before the Web,
                        when you had very little chance of reading a document written on another
                        computer, another word processor, or another network. -- Tim Berners-Lee

                        Comment

                        • dhtml

                          #13
                          Re: Closures Explained

                          Thomas 'PointedEars' Lahn wrote:
                          dhtml wrote:
                          >David Mark wrote:
                          >>On Oct 10, 1:06 pm, 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:
                          >>>>http://www.jibbering.com/faq/faq_notes/closures.html
                          >>>Flanagan is listed in the FAQ as the best JavaScript book.
                          >>I thought it was listed as the lesser evil. It is not an endorsement.
                          >http://jibbering.com/faq/#onlineResources
                          >
                          You meant <http://jibbering.com/faq/#books>.
                          >
                          >| Although many books have been reviewed, most are quite bad and cannot
                          >| be recommended.
                          >|
                          >| The following list of books been approved
                          >
                          A "has" was missing if the statement was correct in the first place.
                          >
                          Indeed. Thank you. I did change the text. I found "Pocket Flanagan" was
                          summarily reviewed by JR Stockton and Jim Ley.
                          >by CLJ regulars after critical review.
                          ^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^
                          Double nonsense.
                          >
                          Reviews:





                          Douglas Crockford has provided approval on this list as well. (Though
                          the information is somewhat dated and of an older edition.)


                          D. Flanagan himself has said that the Pocket Reference was "probably out
                          of date."

                          >
                          PointedEars

                          Comment

                          • Thomas 'PointedEars' Lahn

                            #14
                            Re: Closures Explained

                            dhtml wrote:
                            Thomas 'PointedEars' Lahn wrote:
                            >dhtml wrote:
                            >>David Mark wrote:
                            >>>On Oct 10, 1:06 pm, MartinRineh...@ gmail.com wrote:
                            >>>>Flanagan is listed in the FAQ as the best JavaScript book.
                            >>>I thought it was listed as the lesser evil. It is not an endorsement.
                            >>http://jibbering.com/faq/#onlineResources
                            >You meant <http://jibbering.com/faq/#books>.
                            >>
                            >>| Although many books have been reviewed, most are quite bad and cannot
                            >>| be recommended.
                            >>|
                            >>| The following list of books [has] been approved
                            >[...]
                            >>by CLJ regulars after critical review.
                            > ^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^
                            >Double nonsense.
                            >
                            Reviews:


                            http://groups.google.com/group/comp....f145ae807c918e
                            As Lasse already said, those postings (especially comments on a few pages
                            and using that to make assumptions about the rest) do _not_ imply "critical
                            review".
                            Douglas Crockford has provided approval on this list as well. (Though
                            the information is somewhat dated and of an older edition.)
                            http://groups.google.com/group/comp....6d10b261b1a9c8
                            Douglas Crockford may be knowledgable, but he is _not_ "regulars of CLJ",
                            and his posting certainly does _not_ imply "*critical* review". He does not
                            even state the reasons for his recommendation there. Nor does Jim Ley, and
                            given what Flanagan has posted in c.l.js, their judgement becomes rather
                            questionable. Ley's is apparently based on nothing but an "ipse dixit"
                            fallacy. And "not too bad" is certainly no endorsement.
                            D. Flanagan himself has said that the Pocket Reference was "probably out
                            of date."
                            http://groups.google.com/group/comp....e?dmode=source
                            Irrelevant.


                            PointedEars
                            --
                            Prototype.js was written by people who don't know javascript for people
                            who don't know javascript. People who don't know javascript are not
                            the best source of advice on designing systems that use javascript.
                            -- Richard Cornford, cljs, <f806at$ail$1$8 300dec7@news.de mon.co.uk>

                            Comment

                            • Dr J R Stockton

                              #15
                              Re: Closures Explained

                              In comp.lang.javas cript message <be9b7575-f8f6-4c31-950e-9ef78d55626a@k3
                              7g2000hsf.googl egroups.com>, Fri, 10 Oct 2008 10:06:52,
                              MartinRinehart@ 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:
                              >>
                              >http://www.jibbering.com/faq/faq_notes/closures.html
                              >
                              >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.

                              --
                              (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

                              Working...