无法在同一类JS的另一个方法中调用方法 [英] Not able to call method within another method of the same class JS

查看:78
本文介绍了无法在同一类JS的另一个方法中调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在同一类的方法连接中调用方法测试.但是我得到的只是未捕获的类型错误:无法读取未定义的属性'test'". 如何访问sftp回调中的任何变量? 为什么会这样呢?

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?

这是我的代码:

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,您可以轻松地将类上下文共享到内部函数中.

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();
        });
      });
    });


此处是一篇很好的文章,介绍了es6 arrow functions的工作方式以及它们如何影响this.


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

这篇关于无法在同一类JS的另一个方法中调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆