I am pretty familiar with getters and setters in JavaScript, but I am little confused about the behavior I am currently getting. Here is my code:
function u0(n) {
return {
get count() { return ++n; },
set count(m) { m = n; }
}
}
v0 = u0(10); //start with 10
console.log(v0.count); //11: increase by 1
console.log(v0.count); //12: increase by 1
console.log(v0.count); //13: increase by 1
console.log(v0.count = 0); //set back to 0
console.log(v0.count); //14?
When I call the count method and set it, it does reset the count back to zero, but when I call my count method again without setting it, it picks up right where it left off. I was under the impression that when I set the count method it sets n to 0.
Why does count pick up where it left off instead of being reset back to 0 when I set count?
You’re doing it backwards 😉