Tag: Lazy Function Definition Pattern

JavaScript and Russian Dolls

In JavaScript, functions are variables which means they can be created and replaced at run time. Thanks to the pioneering efforts of Richard Cornford (Russian Doll Pattern, 2004), Peter Michaux (Lazy Function Definition pattern, 2007) Oliver Steele (One-Line Memoization, 2006) there are nifty techniques that exploit this capability.

First, a very simple example to illustrate the principle:-

var pushTheRedButton = function() {
    //reassign a new function to the variable pushTheRedButton
    pushTheRedButton = function() {
        //this line gets called on all subsequent visits</span>
        alert("Now look what you've done!");
    //this line only gets called on the first visit</span>
    alert("Don't ever push this button again!");

pushTheRedButton(); //"Don't ever push this button again!"
pushTheRedButton(); //"Now look what you've done!"

Continue reading “JavaScript and Russian Dolls”