var makeCounter = function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
}
};
var Counter1 = makeCounter();
var Counter2 = makeCounter();
console.log(Counter1.value()); /* logs 0 */
Counter1.increment();
Counter1.increment();
console.log(Counter1.value()); /* logs 2 */
Counter1.decrement();
console.log(Counter1.value()); /* logs 1 */
console.log(Counter2.value()); /* logs 0 */
这是MDN上看见的一段函数 js里头的变量 本来是随便获取的,那就没法制造私有变量。
但是这个闭包函数,看实现,privateCounter 这个变量 外面是拿不到的,只能通过调用暴露的接口才能做到,确实通过了这个手法做到了私有变量,蛮有意思的。