SitePoint Sponsor

User Tag List

Results 1 to 7 of 7

Hybrid View

  1. #1
    SitePoint Zealot
    Join Date
    Feb 2011
    Posts
    108
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Explain closures?

    I cannot understand closures even after reading and re-reading a FEW tutorials on the net, what's it's purpose and how do you implement it?

  2. #2
    SitePoint Addict
    Join Date
    Nov 2008
    Location
    Thailand
    Posts
    299
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm glad I'm not the only one. I know I spent a few days of reading from various sources before it finally started to sink in.

    The actual explanantion of how they work, how functions work during invocation , the execution object, the variable object, the scope chain, garbage collection etc, is quite a lot to take in.

    A detailed explanation can be found here Javascript Closures

    In fact at some point you need to stop reading and try them out for yourself.

    The following is an attempt at a simple example. There is more to it.

    Code Java:
    // Closure example
     
    //  Basically functions have what's called a scope chain.
    //  The scope chain links from child to parent all the way to window(global)
    //  So in this case fun2 has access to fun1's x and then to global's y
     
    var y = 5; // global variable
     
    function fun1(){ // has access to y
     
      var x = 0;
     
      return function fun2(){ // has access to x and to y
     
    	  alert(y + x);
    	  x++;
     
      }
     
    };
     
    var test = fun1(); 
    // test calls fun1 and get's the returned function fun2
    // test now forms what is known as closure
    // it has a returned reference to fun2 which
    // in turn has reference to x and to y via it's scope chain.
    // the permanent reference has formed a closure.
     
    // test
    test(); // 5      5 + 0
    test(); // 6      5 + 1
     
    y = 20;
    test(); //22     20 + 2

  3. #3
    SitePoint Zealot
    Join Date
    Feb 2011
    Posts
    108
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks, the first few paragraphs on that page is the best explanation so far, can you or anyone else tell me of actual situation where this would be needed? Also, it absolutely necessary to learn this or can a JS person get by without t or is there an alternative?

  4. #4
    SitePoint Addict
    Join Date
    Nov 2008
    Location
    Thailand
    Posts
    299
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes it's worth learning. Necessary even. Not just for the intentional use of closures but also for the unintentional.

    An example of unintentional

    Code JavaScript:
    <body>
    <h2>click on each of these</h2>
    <ul>
      <li>LI 1</li>
      <li>LI 2</li>
      <li>LI 3</li>
      <li>LI 4</li>
      <li>LI 5</li>
      <li>LI 6</li>
    <ul>
     
    <script type = 'text/javascript'>
    var listItems = document.getElementsByTagName('li'),
          len = listItems.length;
     
    for (var i = 0; i <  len; i += 1){
     
      listItems[i].onclick = function() { alert('Item ' + i); };
     
    }
    </script>
    </body>

  5. #5
    SitePoint Addict
    Join Date
    Nov 2008
    Location
    Thailand
    Posts
    299
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Another example
    With closure
    Code:
    var myFunc = (function(){
    
      var x = the return value of some complicated procedure here;
      
      return function(y){
            
         do something with x  and y here and return the result;
      
      }
    
    }());
    Without closure it might look like this

    Code:
    var myFunc = function(y){
    
      var x = the return value of some complicated procedure here;
      
      do something with x  and y here and return the result;
    
    }
    Each time we call the function without closure we have to not only create a variable x but we have to run through that complicated procedure.

    With the use of closure x is only run once and a reference kept of it in closure.

    A few other uses off the top of my head. Private variables, currying(partial application) and binding.

    I'm sure others here can comment. In fact there's a douglas crockford video which is devoted almost entirely to them, which is well worth a watch. It maybe this one I can't remember http://googlecode.blogspot.com/2009/...ood-parts.html see 0:27

  6. #6
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,705
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by RLM2008 View Post
    I'm sure others here can comment.
    I didn't want to because I couldn't think of a good enough example.
    Fortunately lighting has struck. I'm watching a recent Douglas Crockford video talk that he gave to Etsy about "The Good Parts", and closure is nicely covered in there at around the 38 minute mark.
    Douglas Crockford 4/27/2011 on Etsy - live streaming video powered by Livestream

    To start with, here's a simple function that returns the name of a digit.

    Code javascript:
    var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
     
    var digit_name = function (n) {
        return names[n];
    };

    The problem with that code is that since those variables are not within a function, they are at the global scope. Global variables are in constant danger of being clobbered. Not only by yourself, but potentially from other code that you cannot know of or trust, such as adverts for example.

    So, remove the array from the global scope by putting the array inside the function.

    Code javascript:
    var digit_name = function (n) {
        var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
     
        return names[n];
    };

    Now the names variable is a private variable, but now you're defining an array of ten items every time you want to retrieve one of them. This is where closure comes in.

    With closure, you can return a function that retains knowledge of the variables from within its own scope. This is all built on top of a self-executing function:

    Code javascript:
    var value = (function () {
        return 'value';
    }());

    So the function is executed immediately, which returns as a result the returned value.

    Now instead of returning a value, a function can be returned too.

    Code javascript:
    var digit_name = (function (n) {
        var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
     
        return function () {
            return names[n];
        };
    }());

    Now the outer function is executed immediately, which returns as a result the inner function. That returned function retains knowledge of the names variable, and any other variables that are defined in the same scope.

    Closure is the most powerful idea in JavaScript, which it got from Scheme.

    Some wise words that I heard somewhere is that writing in JavaScript without understanding closure is like writing in Java without understanding classes.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  7. #7
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,705
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by mikehende View Post
    I cannot understand closures even after reading and re-reading a FEW tutorials on the net, what's it's purpose and how do you implement it?
    This is one of the nicest explanations of closure that I've come across.
    How do JavaScript closures work?
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •