Search code examples
javascriptecmascript-6referenceerror

Scope error in constructor (ES6)


I've encountered a strange error while I was working with the new version of ES6. When I run this piece of code I'm getting ReferenceError: alertBox is not defined. Is there any way to call alertBox inside this function? Thanks in advance :)

Here's the code

class main {
    constructor(data){
    this.data=data;

    // this one works
    this.alertBox(this.data);

    this.watchFile(function(){
      // this one throws error
      this.alertBox(this.data);
    });
    }

  alertBox(data){
    alert(data);
  }

  watchFile(cb){
    cb("changed");
  }
}

// app.js
new main("hello");

Here you can find the snippet: https://repl.it/FJUo


Solution

  • By passing a normal function into watchFile you're losing the context of this. In ES6 you can use "arrow function" syntax to create a function which keeps the correct context.

    this.watchFile(() => {
        this.alertBox(this.data);
    });