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 :з
The problem is that when you return {ans}, that's equivalent to writing {ans: ans}, where the second ans 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:
let createCounter = function(init) {
let ans = init
return {
increment(){return ++ans},
decrement(){return --ans},
reset(){return ans = init},
get ans() {return ans},
}
};
myob1=createCounter(3)
myob2=createCounter(10)
console.log(myob1.increment()) // 4
console.log(myob2.increment()) // 11
console.log(myob1.ans) // 4
console.log(myob2.ans) // 11
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With