Reputation: 183
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
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
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