官术网_书友最值得收藏!

Private variables

Closures are frequently used to encapsulate some information as private variables. JavaScript does not allow such encapsulation found in programming languages such as Java or C++, but by using closures, we can achieve similar encapsulation:

function privateTest(){
 var points=0;
  this.getPoints=function(){
    return points;
  };
  this.score=function(){
    points++;
  };
}

var private = new privateTest();
private.score();
console.log(private.points); // undefined
console.log(private.getPoints());

In the preceding example, we are creating a function that we intend to call as a constructor. In this privateTest() function, we are creating a var points=0 variable as a function-scoped variable. This variable is available only in privateTest(). Additionally, we create an accessor function (also called a getter)—getPoints()—this method allows us to read the value of only the points variable from outside privateTest(), making this variable private to the function. However, another method, score(), allows us to modify the value of the private point variable without directly accessing it from outside. This makes it possible for us to write code where a private variable is updated in a controlled fashion. This pattern can be very useful when you are writing libraries where you want to control how variables are accessed based on a contract and pre-established interface.

主站蜘蛛池模板: 安平县| 武城县| 新安县| 舞钢市| 芜湖县| 兴隆县| 乌兰浩特市| 兴城市| 高清| 邻水| 三江| 龙游县| 旬邑县| 德安县| 曲靖市| 大姚县| 无锡市| 桃江县| 瓮安县| 黎城县| 新密市| 凤庆县| 伊吾县| 澳门| 富阳市| 黄骅市| 舞阳县| 连南| 襄汾县| 吐鲁番市| 鄂温| 库伦旗| 南昌市| 宁陵县| 古丈县| 华蓥市| 合水县| 玛沁县| 哈密市| 德令哈市| 波密县|