我正在遵循本教程:https : //www.youtube.com/watch?v=1JsJx1x35c0
但是,当我运行此代码时,它给了我一个错误
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())
我明白了
未捕获的TypeError:counter.value不是函数
这有什么解释?为什么将其counter.value()
视为不是功能?
整个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())
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句