JavaScript object oriented private static variable instance analysis

  • 2020-12-05 17:06:55
  • OfStack

An example of JavaScript object oriented private static variable is presented in this paper. To share for your reference, the details are as follows:

As you know, the principle of private instance variables is based on scope.

Private instance variables are implemented within function of Javascript using the var keyword and are only valid within function.

To mimic this, a solution to private static variables is proposed:


<script language="javascript" type="text/javascript">
var JSClass = (function() {
 var privateStaticVariable = " Private static variable ";
 var privateStaticMethod = function() {
  alert(" Call a private static method ");
 };
 return function() {
  this.test1 = function() {
   return privateStaticVariable;
  }
  this.test2 = function(obj) {
   privateStaticVariable = obj;
  }
  this.test3 = function() {
   privateStaticMethod();
  }
 };
})();
var testObject1 = new JSClass();
var testObject2 = new JSClass();
alert(testObject1.test1());
testObject1.test2(" Changed private static variables ");
alert(testObject2.test1());
testObject2.test3();
</script>

Note that instead of defining the Javascript class directly, you use an anonymous function as a container for static variables and return the Javascript class.

For more information about JavaScript object orientation, see the javascript Object Orientation Tutorial.

I hope this article has been helpful in JavaScript programming.


Related articles: