Peter Michaux has written about the Lazy Function Definition Pattern.
His article takes you down the path of implementing a simple problem:
Write a function foo that returns a Date object that holds the time that foo was first called.
After critiquing 3 iterations he ends up with:
-
-
var foo = function() {
-
var t = new Date();
-
foo = function() {
-
return t;
-
};
-
return foo();
-
};
-
He then uses the technique to implement getScrollX, and to talk about how you can use defineGetter in certain browsers to simulate lazy definition for properties that aren’t functions.