ES6:使用_this_从方法内访问类变量

时间:2015-06-24 18:56:54

标签: javascript ecmascript-6

我们说我在ES6上有这样的课程:

export default class myClass{
    constructor () {
        this.logCount = 0
    }

    log (msg) {
        this.logCount++
        console.log(this.logCount + " - " + msg)
    }
}

为什么this.logCount中的log()未定义,如果我访问它?我在这里缺少什么?

1 个答案:

答案 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)
    }
}

谢谢大家的帮助和建议!