July 6, 2009

Make a javascript function lazy

After reading Oliver Steele's article "One-Line JavaScript Memorization", I recall the similar situation before when I was request to design a JScript registry sytem for a portal site. Adding or setting a transaction in a registry is fast, however, the generation of registry, part of the registry or reindexing is slow. To memorized the previous result is useful in these cases. In order to extend the scope of application, I have rewrite Oliver's code into prototype version.


Adding the prototype of reCalc to avoid any possible error of resetting a calculation method using its reCalc() before makeLazy() is called.


<script type="text/javascript">
Function.prototype.reCalc=function(){};
Function.prototype.makeLazy=function(p){
	var o=this.prototype,f=o[p],m,v,s=function(v){
		return o[p]=v||m
	};((m=function(){
		(s(function(){return v})).reCalc=m.reCalc;return v=f.call(this)
	}).reCalc=s)()
};
</script>

To see what a lazy function look like, you should first create a class. I use the Angle class as described by Steele:


<script type="text/javascript">
Angle=function(){}
Angle.prototype.setRadian = function(radian) {
	this.radian = radian;
	document.write("Calculation again!<"+"br/>");
	this.getDegree.reCalc()
};
Angle.prototype.getDegree = function() {
  return this.radian * 180 / Math.PI;
}
</script>

Since I have defined the reCalc() previous, this class should run as normal. Now, try to make the getDegree() method as a lazy method before creating a new object. The following code to illustrated this:


<script type="text/javascript">
Angle.makeLazy('getDegree');
t=new Angle();
document.write(t.getDegree()+"<"+"br/>")
t.setRadian(1.0);
document.write(t.getDegree()+"<"+"br/>")
document.write(t.getDegree()+"<"+"br/>")
document.write(t.getDegree()+"<"+"
") document.write(t.getDegree()+"<"+"
") document.write(t.getDegree()+"<"+"
") t.setRadian(1.2); document.write(t.getDegree()+"<"+"br/>") </script>

view examplet - online examplet in Cloudgen's Examplet Store(ces)

Today's Visitors: 0 Total Visitors: 20
Personal Category: Javascript Topic: technology / 3C / computers
[Trackback URL]

Post A Comment









Yes No



Please input the magic number:

( Prevent the annoy garbage messages )
( What if you cannot see the numbers? )
Please input the magic number

誰來收藏
Loading ...
unlog_NVPO 0