Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get a value of a let inside an object created with a function?

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 :з

like image 912
stepaks675 Avatar asked Dec 31 '25 15:12

stepaks675


1 Answers

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
like image 88
Andrew Parks Avatar answered Jan 03 '26 14:01

Andrew Parks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!