SoFunction
Updated on 2025-02-28

Lazy function definition mode usage method page 1/3

This article explains a functional-programming design pattern, which I call Lazy Function Definition. I've found this pattern to be very useful in JavaScript more than once, especially when writing cross-browser, efficient libraries.

Warm-up questions

Write a function foo, which returns a Date object, which saves the time when foo is first called.

Method 1: Techniques from ancient times

This most humble solution uses the global variable t to save the Date object. When foo is called for the first time, the time will be saved to t. The next call is called again, foo will only return the value saved in t.
Copy the codeThe code is as follows:

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


But there are two problems with such code. First, the variable t is a redundant global variable and may be changed during the interval between foo calls. Second, the efficiency of these codes is not optimized when called because each call foo must evaluate the conditions. Although the evaluation conditions do not appear inefficient in this example, there are often extremely expensive conditional evaluations in real-world practical examples, such as in the structure of if-else-else-….

Method 2: Module mode

We can make up for the flaws of the first method by module patterns that are considered to be attributed to Cornford and Crockford. Use closures to hide the global variable t, and only code inside foo can access it.

Copy the codeThe code is as follows:

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

But this still does not optimize the efficiency of calling, because each call to foo still requires evaluation conditions.
While module mode is a powerful tool, I firmly believe it is used in the wrong place in this case.
Method 3: Functions as objects
Since JavaScript functions are also objects, they can carry properties, and we can implement a solution with similar quality as module modes.

Copy the codeThe code is as follows:

function foo() { 
    if () { 
        return ; 
    } 
     = new Date(); 
    return ; 


In some cases, a function object with attributes can produce a clearer solution. I think this method is more philosophical than the pattern module method.

This solution avoids the global variable t in the first method, but still cannot solve the conditional evaluation brought by each call of foo.
123Next pageRead the full text