无法弄清楚为什么我无法打印计数

时间:2018-03-21 08:39:54

标签: javascript

function createCounter(countt) {
  var count = countt
  return {
    increment: function() {
      count = count + 1
      //return console.log(count)
    },

    currentValue: function() {
      return console.log(count)
    }
  }
}

var counterStartingAt5 = createCounter(5)

var counterStartingAtMinus2 = createCounter(-2)

为什么我无法打印console.log(count)?如果我在增量或console.log上使用currentValue它不起作用,它只是不打印它。它应该可以访问计数,但由于某种原因它不会返回值...有人可以解释一下吗?

1 个答案:

答案 0 :(得分:4)

在调用currentValue函数之前,它不会打印任何内容。请参阅以下工作示例:

function createCounter(countt) {
  var count = countt
  return {
    increment: function() {
      count = count + 1
      //return console.log(count)
    },

    currentValue: function() {
      return console.log(count)
    }
  }
}

var counterStartingAt5 = createCounter(5);
counterStartingAt5.currentValue();
counterStartingAt5.increment();
counterStartingAt5.currentValue();