Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

es6 Javascript class using this inside a callback [duplicate]

Tags:

The new es6 class allows you to use the self reference variable this inside methods.
However if a class method has a sub function or a callback, that function/callback no longer has access to the self reference variable this

class ClassName {   constructor(dir){     this.dir = dir;     fs.access(this.dir, fs.F_OK | fs.W_OK, this.canReadDir);//nodejs fs.access with callback   }    canReadDir(err){     this.dir;// NO ACCESS to class reference of this   }   //OR   aMethod(){     function aFunc(){       this.dir;// NO ACCESS to class reference of this     }   } } 

Is there any solution to this?

like image 266
fredtma Avatar asked Apr 08 '16 11:04

fredtma


1 Answers

You have the following options:

1) Use an arrow function:

class ClassName {   // ...   aMethod(){     let aFun = () => {       this.dir;// ACCESS to class reference of this     }   } } 

2) Or the bind() method:

class ClassName {   // ...   aMethod(){     var aFun = function() {       this.dir;// ACCESS to class reference of this     }.bind(this);   } } 

3) Store this in a specialised variable:

class ClassName {   // ...   aMethod(){     var self = this;     function aFun() {       self.dir;// ACCESS to class reference of this     }   } } 

This article describes the necessary details about this and arrow functions in JavaScript.

like image 52
Dmitri Pavlutin Avatar answered Sep 27 '22 21:09

Dmitri Pavlutin