1

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

Kost Soto
  • 13
  • 3

1 Answers1

0

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);
});
Graham
  • 6,484
  • 2
  • 35
  • 39
  • Thank you very much! It worked, I didn't know that I have to use arrow functions for that particular reason. Thanks again :) – Kost Soto Jan 14 '17 at 13:33
  • Yep, before ES6 you had to manually bind `this` to a normal function, but with arrow functions you get this behaviour for free. – Graham Jan 14 '17 at 13:36