Static variables in a Javascript class
Yes, that is the correct approach to create private static variables.
However, I would treat the static_fn
different. It seems you want it to be public.
- It should be on your "class"es prototype as it does not interact with private instance variables
- It even does not interact with instances at all. The usual approach is to put such a function/variable on the "class" itself, i.e. the constructor in JS. As the constructor is a
Function
object, it can be extended with properties as any other js object.
var ObjClass = (function closure(){
var static_var = 0; //static private (scoped) variable
function static_fn(){ return static_var; }; //static private (scoped) function
function ObjClass() {
var thisNumber = ++static_var; // private instance variable
this.getThisNumber = function() { // public instance method
return thisNumber; // "privileged" to access scoped instance variables
};
}
ObjClass.getStaticNumber = static_fn; // make the static_fn public
return ObjClass;
})();
var obj1 = new ObjClass;
var obj2 = new ObjClass;
console.log(ObjClass.getStaticNumber()); //output `2`
var obj3 = new ObjClass;
console.log(ObjClass.getStaticNumber()); //output `3`
console.log(obj1.getThisNumber()); //output `1`
console.log(obj2.getThisNumber()); //output `2`
console.log(obj3.getThisNumber()); //output `3`