使用object.assign()添加到对象中的getter发现闭包变量的值错误

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

本文关键字:发现 getter 闭包 变量 错误 对象 assign object 添加 使用      更新时间:2023-09-26

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

这样做:(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