Not able to call method within another method of the same class JS

juldepol picture juldepol · Nov 23, 2017 · Viewed 8.4k times · Source

I am trying to call method test in method connect of the same class. But all I am getting is "Uncaught Type Error: Cannot read property 'test' of undefined". How do I access any variables inside of sftp callback? Why is it so?

Here is my code:

Answer

Orelsanpls picture Orelsanpls · Nov 23, 2017

When using function() { you are getting into a new context which is not your class context. Using es6 arrow functions, you can easily share your class context into inner functions.


  this.client.on('ready', () => {
      client.sftp((err, sftp) => {
        if (err) throw err;

        sftp.readdir('/home/' + username, (err, list) => {
          if (err) throw err;

          this.test('hey');

          client.end();
        });
      });
    });

Here is a good article about how es6 arrow functions works and how they affect this.