jQuery and closures
July 4, 2008 · 11 Comments
Most of my readers will know that I'm a big fan of closures - the ability to create anonymous functions with bound variables (bound in the context of the closure).
David Harris has a brief post about the joys of jQuery where he comments on what, to him, was an unexpected feature that allowed binding of variables, i.e., JavaScript (and ActionScript) support closures. I find it interesting that he thinks this binding "somehow feels wrong" and I've seen the same reaction from a number of people when first confronted with closures.
This binding is what gives closures their power and why they are more than just "anonymous functions". They carry with them the context in which they were created.
It's also an interesting contrast with ColdFusion where variable binding is done at the last minute at runtime and thus you can take a UDF function that references variables.foo (which might be a page scope variable) and add that function to a CFC instance and now variables.foo will refer to foo in the variables scope of the CFC itself.
I think that's why my Closures for CFMX library has proved so puzzling for a lot of folks :)
Tags: coldfusion · jquery

11 responses so far ↓
1 John Farrar // Jul 5, 2008 at 4:57 AM
2 Alan // Jul 5, 2008 at 8:54 AM
I'm conserned that they might pose a memory leak when used often. SInce there is no reference to it, how can it be garbage collected. I can add an event listener for the closure's parent function, but I can't unregister that listener.
Any ideas?
3 Sean Corfield // Jul 5, 2008 at 9:05 AM
4 Alan // Jul 5, 2008 at 1:35 PM
Perhaps it's not an issue for a function rarely called, but I was using it with an enterFrame event and I was unable to stop the event from being called by using a removeEventLListener(Event.ENTER_FRAME, (my function with closure).
Because I was only refering to the enter frame function Indirectly ( only through a parent function) it seemed odd.
Do am I incorrect anywhere?
5 Sean Corfield // Jul 5, 2008 at 2:21 PM
6 Sergio Bonfiglio // Jul 16, 2008 at 6:45 AM
Could you make me a couple of examples ?
Thanks
Sergio
7 Sean Corfield // Jul 16, 2008 at 8:24 AM
http://corfield.org/search/closures
8 David Harris // Jul 20, 2008 at 7:56 PM
I have a friend who is much more clued up on AS3 who gave me some feed back telling me not to use anon functions in AS3.
I'll check up why again and do a follow up blog post, so keep an eye on my blog :-)
9 Sean Corfield // Jul 21, 2008 at 7:41 AM
10 Ben // Oct 19, 2011 at 11:47 AM
Therefore it be a bit redundant saying
'UDF function' ?
11 Sean Corfield // Oct 19, 2011 at 6:44 PM
Leave a Comment