Luke Johnson
Luke Johnson

Reputation: 183

Javascript function closure - access updated variable value in return statement

I'm working with a nested function similar to the one below:

function counter() {
  let count = 0;

  function increment() {
    count++;
  }

  return {
    count: () => count,
    increment: increment
  };
}

const myCounter = counter();
myCounter.increment();
console.log(myCounter.count())

This appears to work fine but is there any way to return the updated count as just the value instead of a function? Ideally the goal is to be able to access the updated count with just myCounter.count instead of myCounter.count()

Upvotes: 2

Views: 69

Answers (2)

xdeepakv
xdeepakv

Reputation: 8135

You can use ES6 class, getter setter to simplify.

class Counter {
  constructor(){
    this._count = 0
  }
  increment() {
    this._count++;
  }
  get count(){
    return this._count;
  }
}


const myCounter = new Counter();
myCounter.increment();
myCounter.increment();
console.log(myCounter.count)

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386730

You could take a getter, which is a function which is called if you use the property.

function counter() {
  let count = 0;

  function increment() {
    count++;
  }

  return {
    get count() { return count },
    increment
  };
}

const myCounter = counter();
myCounter.increment();
console.log(myCounter.count)

Upvotes: 2

Related Questions