- 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.
- PHP動態(tài)網(wǎng)站程序設(shè)計
- OpenShift開發(fā)指南(原書第2版)
- Learn to Create WordPress Themes by Building 5 Projects
- 信息可視化的藝術(shù):信息可視化在英國
- Oracle 12c中文版數(shù)據(jù)庫管理、應(yīng)用與開發(fā)實踐教程 (清華電腦學(xué)堂)
- 編寫高質(zhì)量代碼:改善Python程序的91個建議
- Instant 960 Grid System
- 你必須知道的204個Visual C++開發(fā)問題
- Xamarin.Forms Projects
- HDInsight Essentials(Second Edition)
- 用戶體驗增長:數(shù)字化·智能化·綠色化
- Mastering Python Design Patterns
- Python函數(shù)式編程(第2版)
- Delphi開發(fā)典型模塊大全(修訂版)
- Appcelerator Titanium:Patterns and Best Practices