Tuesday, December 28, 2010

Lazy Function Definition

Lazy Function Definition is a pattern of function definition where a function is not defined properly until you execute it for first time. Assume you have some setup work which you need to do on page load, and you have to do that only once. In such case you can overwrite your function while executing it for first time. 

For example:
Assume that you need a function to return page loaded time, you write a function that get called on page load, and every time you need to refer page loaded time.

var getPageLoadedTime =function (){

var pageLoadedTime = new Date();

getPageLoadedTime=function(){

return pageLoadedTime;

}

}


When you call this function first time, it will set and store pageLoadedTime, and overwrite old function with new one that return the same time on every subsequent calls. This can be very useful when you have to do lot of setting up in your code. Also it can help you in reducing global parameters. 


No comments:

Post a Comment