[Javascript] Hopefully quick question.

Terry Riegel riegel at clearimageonline.com
Mon Oct 5 04:28:11 CDT 2009


Thanks,

This closure thing is very cool. I think I understand it until I start  
using it :)

Your answer is spot on. I will read the links you posted and do some  
testing to see if I can get my head around it.

Terry

http://p8ste.com

On Oct 4, 2009, at 10:31 PM, Noah Sussman <blinkdog at gmail.com> wrote:

> On Sat, Oct 3, 2009 at 2:36 PM, Terry Riegel
> <riegel at clearimageonline.com> wrote:
>> <script>
>>  var obj=$('mydiv');
>>  obj.onclick=function() {
>>   alert(obj.id);
>>  }
>>  obj=$('myotherdiv');
>> </script>
>>
>> Which means when a person clicks on obj the code in that function  
>> will
>> fire, which will alert the LAST value of obj.
>>
>> I want to pass that function the value of obj at the time it is set  
>> up.
>
> Use a closure to capture the current value of the variable.
>
> var obj = $('mydiv');
> obj.onclick=(function () {
>   var localObj = obj;
>   return function (){
>      alert(localObj.id);
>   }
> })();
> obj = $('myotherdiv');
>
> I have posted code that works for me, here
> http://gist.github.com/201796
>
> For an explanation of why this works, start with these 2 articles.
>
> http://www.crockford.com/javascript/private.html
> http://www.jibbering.com/faq/faq_notes/closures.html
>
> Also there is some good information around p. 131 of the Rhino book.
>
>
> -- 
> Noah Sussman
> nerdabout.com
> noah at one more bug dot com
> Writing is the beating heart of online user experience -- @Zeldman
> Software is fiction, it is imagination. -- Richard Gabriel
> _______________________________________________
> Javascript mailing list
> Javascript at lists.evolt.org
> http://lists.evolt.org/mailman/listinfo/javascript



More information about the Javascript mailing list