2

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

3
  • Your function count: () => count is a function that returns by value. Commented Apr 9, 2020 at 15:15
  • @TLane Can you elaborate? I'm not sure what you're trying to say. Commented Apr 9, 2020 at 16:13
  • Your function returns by a copy of count. The lambda function you have returns by value, and it cannot do any sort of this-pointer binding. If you want an object with a function that returns an incremented copy, make it like so: counter = {count: 0, increment: function(){return ++this.count;}} Commented Apr 12, 2020 at 17:30

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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)

4 Comments

True, but OP is (currently, at least) working specifically with the code provided. It may or may not be trivial to adjust the code they're using.
@DaveNewton It s safe and secure and more readable. compare to function. and less error-prone like this. not found. I don't see any point not suggesting something better to learn. I have written also, using ES6. Else it can be done using defined property, which is more complex to understand
Let's OP to deside whether he/she want to learn new thing, rather than stick to old thing.
My point is simple: showing an alternative is fine, but does not directly answer the question (and the more-appropriate answer shows that it's not any more complex).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.