This article describes a functional programming (functional-programming) design pattern, called Lazy Function Definition ). More than once I found this mode useful in JavaScript, especially when writing a cross-browser, efficient library.
Warm-up questions
Compile a function foo, which returns the Date object, which stores the time when foo was called for the first time.
Method 1: Technology in the Ancient Age
The simplest solution uses the global variable t to save the Date object. When foo is called for the first time, the time is saved to t. In the next call, foo only returns the value stored in t.
Copy codeThe Code is as follows:
Var t;
Function foo (){
If (t ){
Return t;
}
T = new Date ();
Return t;
}
But such code has two problems. First, variable t is an extra global variable and may be changed during the interval between calls to foo. Second, the efficiency of the Code during the call is not optimized because each call to foo must evaluate the condition. In this example, the evaluate condition is not inefficient, but in practice in the real world, it is often very expensive to evaluate the condition, for example, in if-else -... .
Method 2: module Mode
We can compensate for the defects of the first method by the module pattern that is attributed to Cornford and Crockford. You can use the closure to hide the global variable t. Only the code in foo can access it.
Copy codeThe Code is as follows:
Var foo = (function (){
Var t;
Return function (){
If (t ){
Return t;
}
T = new Date ();
Return t;
}
})();
However, this still does not optimize the call efficiency, because each call to foo still requires a value condition.
Although the module mode is a powerful tool, I firmly believe that in this case it is used incorrectly.
Method 3: functions as objects
Because JavaScript Functions are also objects, they can have attributes. Therefore, we can implement a solution similar to the module mode quality.
Copy codeThe Code is as follows:
Function foo (){
If (foo. t ){
Return foo. t;
}
Foo. t = new Date ();
Return foo. t;
}
In some cases, function objects with attributes can produce clear solutions. In my opinion, this method is more conceptual than the mode module method.
This solution avoids the global variable t in the first method, but still does not solve the condition evaluation caused by each call of foo.