我正在关注本教程: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())
我明白了
Uncaught TypeError: counter.value is not a function
这怎么解释?为什么它认为 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())
关于JavaScript 闭包 : Uncaught TypeError: counter. 值不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58654226/