我们说我在ES6上有这样的课程:
export default class myClass{
constructor () {
this.logCount = 0
}
log (msg) {
this.logCount++
console.log(this.logCount + " - " + msg)
}
}
为什么this.logCount
中的log()
未定义,如果我访问它?我在这里缺少什么?
答案 0 :(得分:-1)
事实证明问题出现在使用log()
方法的上下文中:
export default class myClass{
constructor () {
this.logCount = 0
}
openSocket() {
let mySocket = new WebSocket('wss:/.../...')
// wrong: because you loose the this-context
// mySocket.onopen= this.log
// correct:
mySocket.onopen= ((evt) => {this.log(evt)})
}
log (msg) {
this.logCount++
console.log(this.logCount + " - " + msg)
}
}
谢谢大家的帮助和建议!