这是有效的(最终结果是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)
答案 0 :(得分:0)
这样做:( 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