A Week in JavaScript Patterns: Lazy Function Definition
Lazy Function Definition is a pattern of functional JavaScript programming, similar to Load Time Configuration. The key difference is that the final function value isn’t configured at load time, but rather upon the first invocation of the function.
The Lazy Function Definition pattern was discovered and named by Peter Michaux.
Motivation
Generally there are two main reasons for wanting to defer defining functions until a later time (although with any pattern, many other applications exist):
- Resources required for a function to be fully defined are not available until the page fully loads or until a user-driven event (for example, determining page scroll).
- The resources created by defining the function are particularly taxing and may not even be needed (for example attaching event handlers).
Implementation
The Lazy Function Definition solves these problems by defining resources upon the first invocation of the function and then redefining itself so that they are not recreated during subsequent calls. All resources are stored via closure so they remain available to the inner function (which becomes the new definition for the outer function).
var getResource = function () {
var resource, counter;
resource = 'foo';
counter = 0;
getResource = function () {
return resource + ' has been accessed ' + (++counter) + ' times';
};
return getResource();
};
In the code above, a getResource function is defined. When the function is called the first time, resource and counter are created to store important information which is needed in future calls to getResource.
The function which immediately follows redefines the original getResource function, but because resource resource and counter are defined in the same scope as the inner function, they remain available.
Finally, the new getResource is executed and it’s value is returned. Now any future calls to getResource will use the inner function.
Conclusion
The Lazy Function Definition pattern allows for deferred function definition as well as insuring that resources that only need to be created once, are created once.
- Sunday: Self-invocation
- Monday: Load Time Configuration
- Tuesday: The Module
- Wednesday: Lazy Function Definition