Examplet Center

Javascript Examplets and Examples

Select the following Topics you are interested

  1. List of all Javascript Examplets and Examples

Javascript Examplet - Make a javascript function lazy

This "Javascript examplet" is extracted from article "Make a javascript function lazy" from Cloudgen's Javascript Laboratory

 


Statement of Goal

To allow a method in a Javascript class to keep the previous result until a reset operating of the method is called.

 


Snippet:

The following is the source code of the snippet. Click the link for downloading the snippet.

<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>

Application Note:

The following is the application code of the snippet.

<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;
}
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()+"<"+"br/>");
document.write(t.getDegree()+"<"+"br/>");
document.write(t.getDegree()+"<"+"br/>");
t.setRadian(1.2);
document.write(t.getDegree()+"<"+"br/>");
</script>

Output:


Copyright 2010 Cloudgen Wong