Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :Đ·

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading