Quantcast
Viewing all articles
Browse latest Browse all 7

Lazy function definition in Javascript

Came across a neat technique in Javascript from Peter Michaux's blog:

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

the idea is that the first time you call foo the function creates an object (in this case a Date instance but it could be something considerably more expensive) and then redefines itself to be a new function that returns that object. His application (which you can read in more detail in his post) is optimizing browser detection/dependent code.


Viewing all articles
Browse latest Browse all 7

Trending Articles