Static Variables in Javascript Class

Is there a proper way to create private static javascript variables (and functions) that don't change no matter how many times you create new Obj ?

Here is what I tried and it seems to work:

 var ObjClass = (function(){ var static_var = 0; //private static variable var static_fn = function(){ return static_var; }; //private static function return function(){ ++static_var; var thisNumber = static_var; this.getThisNumber = function(){ return thisNumber; } this.getStaticNumber = static_fn; //making static fn public } })(); var obj1 = new ObjClass; var obj2 = new ObjClass; var obj3 = new ObjClass; console.log(obj1.getThisNumber()); //output `1` console.log(obj1.getStaticNumber()); //output `3` console.log(obj2.getThisNumber()); //output `2` console.log(obj2.getStaticNumber()); //output `3` console.log(obj3.getThisNumber()); //output `3` console.log(obj3.getStaticNumber()); //output `3` 

Demo

Or is there any other way better ?

+6
source share
2 answers

Yes, this is the right approach to create private static variables.

However, I would consider static_fn different. It seems you want this publicly.

  • It should be on your prototype of the class "class", because it does not interact with private instance variables
  • It does not even interact with instances at all. The usual approach is to put such a function / variable on the "class" itself, i.e. To the constructor in JS. Since the constructor is a Function object, it can be extended using properties like 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` 
+5
source

Earlier, I used this trivial approach to create static variables, except that they are private.

 function MyClass() { var static = this.constructor.static = this.constructor.static || { var1: defValue, ... } static.var1 = ... ; } 

i.e. just save static variables as properties of the primary class constructor function.

+1
source

Source: https://habr.com/ru/post/917099/


All Articles