Search code examples
javascriptclosuresgetter-setter

A getter added to an object with Object.assign() sees the wrong value for a closure variable?


this works (final result is 1)

function jkl() {

    let callCount = 0

    let replacer = {
        get callCount() { return callCount },
    }

    Object.assign(replacer, {
        count() { ++callCount },
    })

    return replacer
}

j = jkl()
j.count()
j.callCount // 1

but this doesn't (final result is 0)

function abc() {

    let callCount = 0

    let replacer = {
        count() { ++callCount },
    }

    Object.assign(replacer, {
        get callCount() { return callCount },
    })

    return replacer
}

a = abc()
a.count()
a.callCount // 0

Any idea why the 2nd one doesn't work as intended?

(i've tried some other ways of doing the same thing and they're all here https://tonicdev.com/nfc/assign-get-closure )


Solution

  • Do it like this: (assign does not work for this)

    Object.defineProperty()

    "use strict"
    
    function abc() {
    
        let callCount = 0
    
        let replacer = {
            count() { ++callCount },
        }
    
        Object.defineProperty(replacer, 'callCount', {
            get: function() { return callCount }
        })
    
        return replacer
    }
    
    var a = abc()
    a.count()
    console.log(a.callCount) // 1