在經典的面向物件程式設計中,經常需要將物件的某個狀態封裝或隱藏在物件內,只有通過物件的方法才能訪問這些狀態,對外只暴露一些重要的狀態可以直接編寫。這是就需要私有狀態。

function Range(from, to){
this.from = function(){return from;}
this.to = function(){return to;}
} Range.prototype = {
constructor: Range,
includes:function(x){return this.from() <= x && x <= this.to();},
foreach:function(f){
for(var x = Math.ceil(this.from()),max = this.to();x < max;x++)f(x);
},
toString:function(){
return "(" + this.from() + "..." + this.to() + ")";
}
}