Lazy definition function
This has a nice name – a lazy function definition. A lazy function is one that pretends to work but it doesn't really.
It does some work initially and then caches the result. Then on consecutive calls it only returns the pre-computed result, it doesn’t really do anything.
In order to do so, the function redefines itself with a new implementation, one that simply points to the computed result.
function lazy() { var result = 2 + 2; lazy = function() { return result; }; return lazy(); } lazy(); // 4 lazy(); // 4
Tags: Functions, lazy definition
January 18th, 2010 at 10:27 am
Hi Stoyan Stefanov
please answer me a question : What is Lazy definition function used for? and when we use it ?
March 18th, 2010 at 10:41 am
[...] http://www.jspatterns.com/lazy-definition-function/ [...]
March 29th, 2010 at 6:57 am
What is the difference between lazy definition functions and closures? They looks too similar.
April 19th, 2010 at 5:59 pm
This pattern can be useful when dealing with cross-browser code. For instance, getting the XmlHttpRequest() object. You could wrap the code for searching the correct object in the initial code and return the caching of the final object. Like this for instance:
ns.getXHRObject = function() {
if (typeof(window.XMLHttpRequest) === “function”) {
// Native object exists
ns.getXHRObject = function() {
return new window.XMLHttpRequest();
};
}
else {
// Do your older browser searching here and replace the outcome with
// a similar new function definition as above..
}
};
Next time the function is called, the caching is returned. So execution will be faster the
second time.. imagine doing this for functions which will do lots of logic over and over again with the same outcome.. this can save lots of cpu cycles.. and better yet, improve user experience..
November 10th, 2010 at 7:45 am
Function is a function. It should be used to do or calculate something. To store result we have variables
November 13th, 2011 at 4:14 am
The video card (sometimes referred to as the GPU) is yet another vital component in any gaming rig, as it handles nearly all of the graphics for your video game titles. A person of the issues with video cards – in particular the center and minimal end ones – is that they tend to come to be obsolete faster than the other components of a gaming pc. Commonly, acquiring a higher conclusion video card when you are upgrading or building your gaming rig is vital as it presents you breathing region in advance of it’s time to upgrade once more.
December 15th, 2011 at 12:07 pm
Hi my loved one! I want to say that this article is awesome, great written and come with approximately all important infos. I’d like to look more posts like this.