如何在此闭包的返回值中访问函数

时间:2019-06-10 16:30:40

标签: javascript function closures

我试图在此闭包的返回值中调用任何函数,但是我无法:

function count() {
  var x = 0;
  return {
    increment: function() { ++x; },
    decrement: function() { --x; },
    get: function() { return x; },
    reset: function() { x = 0; }
  }
}

我怎么称呼“ increment()”,以便它返回“ x”的增量值? 我尝试过:

  • var l = count();,然后是l.increment();,它会返回undefined

1 个答案:

答案 0 :(得分:1)

您的函数有效,但不返回任何内容。您必须使用get()来获取当前值:

function count() {
  var x = 0;
  return {
    increment: function() { ++x; },
    decrement: function() { --x; },
    get: function() { return x; },
    reset: function() { x = 0; }
  }
}

let test= count();
console.log(test.get());
test.increment();
console.log(test.get());
test.increment();
console.log(test.get());
test.decrement();
console.log(test.get());
test.reset();

console.log(test.get());

但是您可以在每个函数中返回新值:

function count() {
  var x = 0;
  return {
    increment: function() { return ++x; },
    decrement: function() { return --x; },
    get: function() { return x; },
    reset: function() { return x = 0; }
  }
}

let test= count();
console.log(test.get());
console.log(test.increment());
console.log(test.increment());
console.log(test.increment());

console.log(test.decrement());

console.log(test.reset());