简体   繁体   English

在 JavaScript 中调用该方法内的方法

[英]Call method inside that method in JavaScript

Consider this:考虑一下:

class ConnectUser {
    connect = () => {
        axios.get('URL').catch(err => {
            // CAN I CALL `connect` METHOD AGAIN?!
            // this.connect();
        });
    }
}

My code has a method and can connect or refuse to connect to some resources.我的代码有一个方法,可以连接或拒绝连接某些资源。 If an exception happens can I call it again to strive for connecting?如果发生异常,我可以再次调用它来争取连接吗?

As an alternative to Danielo's answer - if you want this inside connect to refer to the class instance, you can simply define connect as a method of the class, ie作为 Danielo 答案的替代方案 - 如果您希望this内部connect引用 class 实例,您可以简单地将connect定义为 class 的方法,即

class ConnectUser {
    connect() {
        axios.get('URL').catch(err => {
            return this.connect();
        });
    }
}

Yes, you can.是的你可以。 But if this is something you want to generalize on your app, consider using an axios plugin that automatically retries and only fails after the amount of retries you specify.但是,如果这是您想在您的应用程序上推广的内容,请考虑使用 axios插件,该插件会自动重试,并且仅在您指定的重试次数后才会失败。 You can call just connect function again if you define it as a separate function on the scope instead of a class method.如果您将其定义为 scope 上的单独 function 而不是 ZA142F2ED4F8EBC0C2 方法,则可以再次调用仅连接 function。 But if you really need to call using this, save the proper this reference in the outer closure like this:但是,如果你真的需要使用 this 调用,请将正确的 this 引用保存在外部闭包中,如下所示:

connect = () => {
      const self = this 
        axios.get('URL').catch(err => {
            self.connect();
        });
    } 

Then use self instead然后使用 self 代替

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM