Lazy Function Definition

August 15, 2007 on 8:25 am | In ajax |

From Peter Michaux comes a great article on the Lazy Function Definition pattern for JavaScript, an efficient way to use functional language coolness to avoid potentially expensive conditional checks or global namespace pollution. For example:


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

becomes

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

That’s so clean. Of course, this specific example isn’t hugely useful from a performance perspective, but Peter also provides a page scroll implementation that likely would have a tangible speed boost.

No Comments yet »

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by WordPress with Pool theme design by Borja Fernandez.
Entries and comments feeds. Valid XHTML and CSS. ^Top^