- JavaScript:Moving to ES2015
- Ved Antani Simon Timms Narayan Prusty
- 201字
- 2021-07-09 19:07:33
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.
- Python快樂編程:人工智能深度學習基礎
- 摩登創客:與智能手機和平板電腦共舞
- HTML5+CSS3網站設計基礎教程
- D3.js 4.x Data Visualization(Third Edition)
- C++從入門到精通(第5版)
- 輕松上手2D游戲開發:Unity入門
- Scala Data Analysis Cookbook
- 計算機應用基礎教程(Windows 7+Office 2010)
- INSTANT Apache Hive Essentials How-to
- C# 7.1 and .NET Core 2.0:Modern Cross-Platform Development(Third Edition)
- 分布式數據庫HBase案例教程
- PHP動態網站開發實踐教程
- Learning WordPress REST API
- 你必須知道的.NET(第2版)
- Learning Redux