Home  >  Article  >  Web Front-end  >  JavaScript object-oriented private static variable instance analysis_javascript skills

JavaScript object-oriented private static variable instance analysis_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:20:011543browse

This article analyzes object-oriented private static variables in JavaScript with examples. Share it with everyone for your reference, the details are as follows:

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

Private instance variables are implemented using the var keyword inside a Javascript function and are only valid inside the function.

Imitate this and propose a solution of private static variables:

<script language="javascript" type="text/javascript">
var JSClass = (function() {
 var privateStaticVariable = "私有静态变量";
 var privateStaticMethod = function() {
  alert("调用私有静态方法");
 };
 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("改变的私有静态变量");
alert(testObject2.test1());
testObject2.test3();
</script>

Note that instead of defining the Javascript class directly, an anonymous function is used as a container for static variables and returns the Javascript class .

Readers who are interested in more content related to object-oriented JavaScript can check out the special topic of this website : "Javascript Object-oriented Introductory Tutorial"

I hope this article will be helpful to everyone in JavaScript programming.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn