I want to understand better the mechanics of values inside objects created with funcitons.
let createCounter = function(init) {
let ans = init
return {
increment(){return ++ans},
decrement(){return --ans},
reset(){return ans = init},
ans,
}
};
myob1=createCounter(3)
myob2=createCounter(10)
console.log(myob1.increment()) // 4
console.log(myob2.increment()) // 11
console.log(myob1.ans) // 3
console.log(myob2.ans) // 10
Does the value of ‘ans’ property stay constant after creating an object?
Can i directly get it’s current value within this syntax?
As I understood the value of the let is bond with each object after creating and when I try to get it’s value using object property, it simply appeals to the ‘ans=init’ and displays starting value?
BTW i’m in the very beggining of my JS studying, please don’t be angry on me :з
2
Answers
The problem is that when you return
{ans}
, that’s equivalent to writing{ans: ans}
, where the secondans
references the current value of ans.This means that when you later assign a different value to
ans
, the object{ans}
still references the initial value.To resolve this, use a getter. Change
{ans}
to{get ans() {return ans}}
like this:What you are returning actually is this :
So when you update the value of
ans
, you don’t update the value that was passed in the object (because the function has already computed its return value) but only the variableans
present in the functionTo access the attribute
ans
of the object, you should usethis
(just like if you are in a class)Andrew Parks solution works as well. Both approachs can be used