Search

5/31/2010

Lazy Function Definition Pattern

Lazy Function Definition Pattern


var foo = function() {
var t = new Date();
foo = function() {
return t;
};
return foo();
};

When foo is called the first time, we instantiate a new Date object and reassign foo to a new function which has that Date object in it's closure. Then before the end of the first call to foo the new function value of foo is called and supplies the return value.

Subsequent calls to foo simply return the value of t that is stored in it's closure. This is a fast lookup and efficient especially if the conditionals used in the previous solutions are many and complex.

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" loosely comes from Scheme's lazy evaluation mechanism. Any JavaScript programmer really ought to study Scheme as there is more written about functional programming for Scheme then exists for JavaScript.

Enhanced Javascript Lazy Function Definition Pattern
The lazy function definition pattern is pretty simple at heart: you have a function which does some work, caches the results through a closure variable, and then overwrites itself with a new function that simply returns the closure variable. So the first time you run a function will be the only time the function does any work. Each subsequent call is “lazy” and just returns the results of that first call.

沒有留言: