我试图在同一个类的方法连接中调用方法测试。但我得到的只是“未捕获的类型错误:无法读取未定义的属性‘测试’”。如何访问 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();