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

Popular posts from this blog

java - is not an enclosing class / new Intent Cannot Resolve Constructor -

python - Error importing VideoFileClip from moviepy : AttributeError: 'PermissionError' object has no attribute 'message' -

qt - QML MouseArea onWheel event not working properly when inside QML Scrollview -