使用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
不适用于此)
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
相关文章:
- 查看JS对象的所有键,甚至是getter定义的键
- "实例范围”;TypeScript类的getter/setter
- javascript从任何嵌入式flash视频中发现.flvurl
- 用于发现哪个JS/jQuery脚本正在冻结页面的工具或技术
- 重写不带defineProperty的对象getter
- 我需要一个jQuery函数来只工作在700px以上的屏幕大小,无法在我的代码中发现错误
- 我发现了一些只在移动设备上可见的垃圾邮件链接,我可以'找不到包含此垃圾邮件链接的脚本的位置
- 如何在Node.js控制台中发现Object API
- 在文件中发现此恶意javascript..它做什么
- Chrome审核:在外部CSS文件之间的头中发现了1个内联脚本块&”;
- 无法读取属性'编译'的未定义.可以'我似乎没有发现错误
- 如何发现用户是否使用jQuery滚动到HTML容器的末尾
- 我的代码很完美,但我现在不知道为什么我发现了问题
- 如何防止在javascript中执行继承属性的getter-setter方法
- 从angularjs文件调用apicontroller时未发现错误
- 如何发现至少有一个复选框被选中或没有使用javascript
- 有人能发现我的错误吗(自动完成文本框)
- 过度杀戮?使用indexOf()来发现字符串的内容
- JavaScript 对象中的私有成员,带有 getter 和 setter
- 使用object.assign()添加到对象中的getter发现闭包变量的值错误