javascript - Scope error in constructor (ES6) -
this question has answer here:
i've encountered strange error while working new version of es6. when run piece of code i'm getting referenceerror: alertbox not defined
. there way call alertbox inside function? in advance :)
here's code
class main { constructor(data){ this.data=data; // 1 works this.alertbox(this.data); this.watchfile(function(){ // 1 throws error this.alertbox(this.data); }); } alertbox(data){ alert(data); } watchfile(cb){ cb("changed"); } } // app.js new main("hello");
here can find snippet: https://repl.it/fjuo
by passing normal function watchfile
you're losing context of this
. in es6 can use "arrow function" syntax create function keeps correct context.
this.watchfile(() => { this.alertbox(this.data); });
Comments
Post a Comment