skip to Main Content

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


  1. 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
    Login or Signup to reply.
  2. What you are returning actually is this :

    {
            increment(){return ++ans},
            decrement(){return --ans},
            reset(){return ans = init},
            ans: 3 // if init was 3,
    }
    

    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 variable ans present in the function

    To access the attribute ans of the object, you should use this (just like if you are in a class)

    let createCounter = function(init) {
        let ans = init
        return {
            increment(){return ++this.ans},
            decrement(){return --this.ans},
            reset(){return this.ans = init},
            ans,
        }
    };
    

    Andrew Parks solution works as well. Both approachs can be used

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search