JavaScript 闭包:未捕获的类型错误:counter.value 不是函数

我正在关注本教程: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())

我明白了


未捕获的类型错误:counter.value 不是函数


这有什么解释?为什么它认为counter.value()不是一个函数?


慕莱坞森
浏览 248回答 2
2回答

ibeautiful

整个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())

明月笑刀无情

为了在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        }     }})()`
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript