JavaScript lazy function definition
I've been off for most of the past week as my mom had our boys (keeping all the grandkids together for the week, frighteningly enough), and my wife and I took the opportunity to do some house-hunting. We're looking for something with a bit more yard space for the boys to play in.
I've been offline a lot this week, but I did see an interesting post by Peter Michaux (creator of the Fork JavaScript library ), about lazy function definition in JavaScript .
This is a flavor of self-modifying code where on initial invocation a function actually redefines itself before executing and returning a value. On subsequent calls, it simply executes according to the updated definition. Peter's very simple first example looks like this:
var
foo =
function
() {
var
t =
new
Date();
foo =
function
() {
return
t;
};
return
foo();
};
Peter writes:
Another way of thinking about this this pattern is that the outer function that is first assigned to foo is a promise. It promises that the first time it is run it will redefine foo to a more useful function.
The term 'promise' he uses is a reference to lazy evaluation in languages like Scheme .
An obvious use for this pattern would be library code that paves over differences between browsers. (Peter's final example is a cross-browser function that gets the page scroll.) Having the function tailor itself for the specific browser allows you to avoid a conditional check for what browser every time the function is invoked.
This pattern might be a bit acrobatic for some people's taste -- it's arguably better to be clear than to be clever, particularly in code that lots of people will be touching. But it never hurts to have another powerful tool like this in the toolbox.