无法在同一类 JS 的另一个方法中调用方法

jul*_*pol 3 javascript oop node.js ssh2-sftp

我试图在同一个类的方法连接中调用方法测试。但我得到的只是“未捕获的类型错误:无法读取未定义的属性‘test’”。如何访问 sftp 回调中的任何变量?为什么会这样?

这是我的代码:

const SSH2 = require('ssh2').Client;
class SshClient {
  constructor(host, username, password) {
    this.host = host;
    this.username = username;
    this.password = password;
    this.port = 22;
    this.client = null;
  }

  test(testvar) {
    console.log(testvar);
  }

  connect() {
    this.client = new SSH2();
    let client = this.client;
    let username = this.username;
    this.client.connect({
      host: this.host,
      port: this.port,
      username: this.username,
      password: this.password
    });
    this.client.on('ready', function() {
      console.log('Client :: ready', client);
      client.sftp(function(err, sftp) {
        if (err) throw err;
        sftp.readdir('/home/' + username, function(err, list) {
          if (err) throw err;
          console.dir(list);
          this.test('hey');
          client.end();
        });
      });
    });
  }
}

let ssh = new SshClient('host', 'username', 'password');
ssh.connect();
Run Code Online (Sandbox Code Playgroud)

Gré*_*EUT 5

使用时,function() {您将进入一个新的上下文,这不是您的类上下文。使用es6 arrow 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();
        });
      });
    });
Run Code Online (Sandbox Code Playgroud)

是一篇关于如何es6 arrow functions工作以及它们如何影响的好文章this