参考GPT和自己的思路:
问题的根本在于在 closeMenu 方法中的 this 关键字。在这个方法中,this 指向的是 document 对象,而不是 SelectMenu 实例对象。因此,this.show.value 会报错,因为 document 对象上并没有 show 属性。
解决这个问题的简单方法是,将 closeMenu 方法的 this 绑定到 SelectMenu 实例上,可以使用 bind 方法或箭头函数实现:
- 使用 bind
class SelectMenu {
constructor() {
this.closeMenu = this.closeMenu.bind(this)
}
}
- 使用箭头函数
class SelectMenu {
constructor() {
this.closeMenu = () => {
console.log('this.show.value:', this.show)
this.show.value = false
document.removeEventListener('mousedown', this.closeMenu)
}
}
}
使用这两种方法可以确保 closeMenu 方法中的 this 绑定到正确的对象上,并且能够正确修改 show 属性。