我试图在同一类的方法 connect 中调用方法 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();
使用时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();
});
});
});
Here https://derickbailey.com/2015/09/28/do-es6-arrow-functions-really-solve-this-in-javascript/是一篇关于如何es6 arrow functions
工作原理以及它们如何影响this
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)