3

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 is this.logCount in log() undefined if I access it? What am I missing here?

Benvorth
  • 7,416
  • 8
  • 49
  • 70
  • How are you running this? Granted, it's just an emulator but http://www.es6fiddle.net/ibb4xekt/ runs your code without errors. – Jan Jun 24 '15 at 19:10
  • I transpile this with babel.js during a build-process with webpack (alog an example from http://learn.humanjavascript.com) – Benvorth Jun 24 '15 at 19:14
  • Then I'd look at the requirements and documentation of those tools, As far as E6 goes I see nothing wrong with your code (except missing semicolons). I mean, I'm new to it but it looks allright and works in an emulator so I would look elsewhere for the problem. – Jan Jun 24 '15 at 19:18
  • Your code runs fine in the [babel repl](http://babeljs.io/repl/#?experimental=true&evaluate=true&loose=false&spec=false&code=class%20MyClass%20%7B%0A%20%20%20%20constructor%20()%20%7B%0A%20%20%20%20%20%20%20%20this.logCount%20%3D%200%3B%0A%20%20%20%20%7D%0A%0A%20%20%20%20log%20(msg)%20%7B%0A%20%20%20%20%20%20%20%20this.logCount%2B%2B%3B%0A%20%20%20%20%20%20%20%20console.log(this.logCount%20%2B%20%22%20-%20%22%20%2B%20msg)%3B%0A%20%20%20%20%7D%0A%7D%0A%0Avar%20m%20%3D%20new%20MyClass()%3B%0Am.log(%22hello%22)%3B%0Am.log(%22hello%22)%3B%0Am.log(%22hello%22)%3B) – Mulan Jun 24 '15 at 19:22
  • Thanks for your comments, it seems I run an older version of babel.js – Benvorth Jun 24 '15 at 19:25
  • How are you calling `inst.log()`? You'll still need to ensure that you are calling `log` with the proper context. – loganfsmyth Jun 24 '15 at 19:29
  • at another place in my code I do a `import myClass from './myClass'` and then `let mc = new myClass(); mc.log('foo');` – Benvorth Jun 24 '15 at 19:34

1 Answers1

-1

It turned out the Problem was in the context the log() method was used:

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

Thank you everybody for your help and suggestions!!

Benvorth
  • 7,416
  • 8
  • 49
  • 70