使用 Object.assign() 添加到对象的 getter 会看到错误的闭包变量值?
A getter added to an object with Object.assign() sees the wrong value for a closure variable?
这个有效(最终结果是 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
不适用于此)
"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
这个有效(最终结果是 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
不适用于此)
"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