2 回答
TA贡献1993条经验 获得超5个赞
整个counter表达式的计算结果是一个函数,而不是一个对象,并且该函数没有value属性。如果您调用该函数,value将返回一个具有属性的对象,但您并没有这样做。
您需要立即调用该函数,作为 IIFE,以便counter变量名称引用返回的对象:
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.value())
counter.increment()
counter.increment()
console.log(counter.value())
counter.decrement()
console.log(counter.value())
如果您想创建多个计数器,您可以像现在一样在开始时不调用该函数,但是最好调用它makeCounter而不是counter:
var makeCounter = function() {
var privateCounter = 0
function changeBy(val) {
privateCounter += val
}
return {
increment: function() {
changeBy(1)
},
decrement: function() {
changeBy(-1)
},
value: function() {
return privateCounter
}
}
};
const counter1 = makeCounter();
console.log(counter1.value())
counter1.increment()
counter1.increment()
console.log(counter1.value())
counter1.decrement()
console.log(counter1.value())
console.log('----');
const counter2 = makeCounter();
counter2.decrement();
counter2.decrement();
console.log(counter2.value())
TA贡献1828条经验 获得超4个赞
为了在counter函数上创建一个闭包环境,它必须是一个 IIFE。可能是复制和粘贴的错字。更正:
`var counter = (function(){
var privateCounter = 0
function changeBy(val){
privateCounter += val
}`
`return {
increment: function(){
changeBy(1)
},
decrement: function(){
changeBy(-1)
},
value: function(){
return privateCounter
}
}
})()`
添加回答
举报