var Counter = function(){
var privateCounter = 0;
function changeBy(val){
privateCounter += val;
}
return {
increment:function(){
changeBy(1);
},
decrement:function(){
changeBy(-1);
},
value:function(){
return privateCounter;
}
};
};
console.log(Counter);
ƒ (){
var privateCounter = 0;
function changeBy(val){
privateCounter += val;
}
return {
increment:function(){
changeBy(1);
},
decrement:function(){
changeBy(-1);
…
console.log(Counter())
{increment: ƒ, decrement: ƒ, value: ƒ}
console.log(Counter().value)
ƒ (){
return privateCounter;
}
console.log(Counter().increment())
console.log(Counter().value())
0
因为这里每次都是一个新的对象来调用方法,所以value并没有被加1,我们要如下写法,把Counter直接定义为一个json对象:这个对象中有三个属性,属性值都是方法,并且都是在操作privateCounter属性,所以达到了私有属性的效果。
var Counter = function(){
var privateCounter =0;
function changeBy(val){
privateCounter += val;
}
return {
increment:function(){
changeBy(1);
},
decrement:function(){
changeBy(-1);
},
value:function(){
return privateCounter;
}
};
}();
console.log(Counter)
{increment: ƒ, decrement: ƒ, value: ƒ}
console.log(Counter.increment())
undefined
console.log(Counter.value())
1
成功。