Select the following Topics you are interested
This "Javascript examplet" is extracted from article "Make a javascript function lazy" from Cloudgen's Javascript Laboratory
To allow a method in a Javascript class to keep the previous result until a reset operating of the method is called.
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>
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>