March 26, 2004

Coderefs in Javascript

This may be old hat to you, but I didn’t know it. JavaScript since 1.2 has had the equivalent of Perl code references, or function pointers, that you can pass around and execute as needed. Among other things, this makes it easy to create a generic library while customizing it with a callback:

var aCallback = null;
function registerCallback( cb ) {
    aCallback = cb;
function doSomeLibraryStuff( foo, bar ) {
    // do some stuff
    if ( aCallback != null ) {
        aCallback( foo, bar );

So in your library you can just register your custom functionality and it gets executed whenever the doSomeLibraryStuff function is run:

registerCallback( function( foo, bar ) {
    if ( foo < bar ) {
        alert( "All your base" );

You can also use a Function object for this, but the constructor uses a list of Strings that get joined with a ';' and eval'd into existence. Ugly. And these support closures as well.

Next: Good weekend reading
Previous: Stooping lower and lower... and it's only March!