ES6: Accessing Variable Classes from within a Method with _this_

Let's say I have a class in ES6 like this:

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

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

      

Why this.logCount

in log()

undefined, if I speak to him? What am I missing here?

+3


source to share


1 answer


It turned out that the problem was in the context of using the method 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)
    }
}

      



Thanks everyone for your help and suggestions!

-1


source







All Articles