[Javascript] Hopefully quick question.

Noah Sussman blinkdog at gmail.com
Sun Oct 4 21:31:32 CDT 2009


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



More information about the Javascript mailing list