使用Object.assign()添加到对象的getter会看到闭包变量的错误值?

时间:2016-01-02 10:15:53

标签: javascript closures getter-setter

这是有效的(最终结果是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

但这不是(最终结果是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

知道为什么第二个不按预期工作?

(我尝试了其他一些做同样事情的方法,他们都在这里https://tonicdev.com/nfc/assign-get-closure

1 个答案:

答案 0 :(得分:0)

这样做:( assign不起作用)

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