Ajax Talk - Asynchronous javascript and xml discussion board
 FAQ   Search    Usergroups      Register   Profile   Check your messages   Log in 
Signup now to enjoy a range of free membership advantages !!
Ajax Talk - Moderators Wanted
Closures - in JavaScript, Not in Relationships

 
Post new topic   Reply to topic    Ajaxtalk.com Forum Index -> AJAX Programmers Exchange
View previous topic :: View next topic  
Author Message
Jesdisciple
Frequent Poster
Frequent Poster


Joined: 20 Oct 2007
Posts: 36
Location: Tejas

PostPosted: Sun Dec 09, 2007 11:52 pm    Post subject: Closures - in JavaScript, Not in Relationships Reply with quote

Closures are a fairly advanced JavaScript feature which I have only seen discussed in special articles rather than tutorials. (Before anyone asks, I don't know how they got that name.) While I wish someone would write a tutorial that would introduce beginners to the concept, I don't have the time and might not have the expertise, so this is going to follow that trend.

First, let's have a definition. A closure is the scope of an outer function made accessible to all inner functions. When I look at code which uses closures, it seems like common sense that outer variables would be available from inner functions, but, at the same time, I wouldn't expect the effect sometimes. The effect can manifest similarly to the private declaration of properties in PHP or Java, or the static declaration of PHP as used at the first of a PHP function. Like both of these, a closure allows variables to be accessible only from within a certain context, across repeated calls to a certain set of functions.

JavaScript With(out) Closures
If JavaScript is written strictly without using closures, it's considerably limited as far as privacy. Let's say I want to return Function B from Function A, then call Function B to manipulate variables initialized in Function A. (What a mouthful.)
Code:
<html>
   <head>
      <title>Titled Document</title>
      <script type="text/javascript">
         function funcA(){
            window.varA = 'a variable';
            function funcB(){
               alert(varA);
            }
            return funcB;
         }
         function main(){
            var funcB = funcA();
            alert(varA + '... Uh-oh...');
            funcB();
         }
      </script>
   </head>
   <body onload="main();">
      
   </body>
</html>
(The mention of window is unnecessary, but I want to make it obvious that varA is global.) This works, but, as the call to alert in main shows, it also exposes your variables to overwriting (and hacking, but a hacker can always overwrite your functions anyway). This is a more private way to do it:
Code:
<html>
   <head>
      <title>Titled Document</title>
      <script type="text/javascript">
         function funcA(){
            var varA = 'a variable';
            function funcB(){
               alert(varA);
            }
            return funcB;
         }
         function main(){
            var funcB = funcA();
//            alert(varA + '... Uh-oh...');
            funcB();
         }
      </script>
   </head>
   <body onload="main();">
      
   </body>
</html>
Uncommenting the call to alert in main causes an error, because varA is only defined within funcB. Closures allow you to set up code boundaries at your convenience.

Final Notes
Pay attention if you declare several inner functions in one outer, particularly in a loop; the closure is a variable scope (as it exists when the inner function in question is executed) rather than a permanent snapshot of that scope from when the function was declared, and so there is one per call to the outer function, not one per inner function per call to the outer function. So this doesn't work as it would if closures were snapshots specific to inner functions:
Code:
var demos = [];
for(var i0 = 0; i0 < 10; i0++){
   demos[i0] = function(){
      alert(i0);
   };
}
for(demo in demos){
   demo();
}
Here's a correct solution to accomplish this in similar steps (but without using the closure):
Code:
var demos = [];
for(var i0 = 0; i0 < 10; i0++){
   demos[i0] = {
      func: function(){
         alert(this.num);
      },
      num: i0
   };
}
for(demo in demos){
   demo.func();
}


Here's a loop-less function that expects a snapshot instead of the actual scope:
Code:
function loopyLoopless(){
   var i = 0;
   function result(){
      alert(i);//should alert 0
   }
   i = 1;
   return result;
}

//user code
loopyLoopless()();//alerts 1 - The JavaScript interpreter must be broken!
And here's a correct version that preserves the user's control over when and in what context the resulting function is executed (while still using a closure):
Code:
function loopless(callback){
   var i = 0;
   callback(function(){
         alert(i);//should alert 0
      });
   i = 1;
}

//user code
loopless(function(result){
      result();//alerts 0
   });


As usual, discussion is invited.
_________________
In ALL things, strive for ><>,
Chris
Back to top
View user's profile Send private message Visit poster's website AIM Address MSN Messenger
Display posts from previous:   
Post new topic   Reply to topic    Ajaxtalk.com Forum Index -> AJAX Programmers Exchange All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
 Advertisements
 XML & Copyright Notice 
    


Powered by phpBB © 2001, 2005 phpBB Group

What is according to Wikipedia: Ajax Web2.0 XML E4X


Link to our site:

  


del.icio.us digg spurl wists simpy newsvine blinklist furl blogmarks yahoo! myweb smarking ma.gnolia segnalo reddit fark technorati cosmos


Normal Bookmark


Partner Button Links:
Codecrunch.com: Webmaster Tutorials    One Ajax


Partner Text Links:
quomon | web20log | ajaxmatters | tableless | 456bereastreet | music charts | gift ideas | competitions | free xbox 360 | link trade ?


Credits:
it consultancy & project management lead generation zoekmachine optimalisatie steal these buttons seo expert