2009-10-11

Static variable in a Javascript object function

Consider the code bellow:

function myfunction(){
var myvariable=19.21;
this.mymethod = function(){ return myvariable; };
this.increase = function(amount){ myvariable+=amount; };
}
var f = new myfunction();
document.write("initial value is " + f.mymethod());
f.increase(0.80);
document.write("<br/>new value is " + f.mymethod());


Because the function myfunction is used as a class for the object f, the local variable myvariable is considered private and it can be accessed only by member functions like mymethod and increase. Therefore this code produces something like this:


Niciun comentariu: