代码之家  ›  专栏  ›  技术社区  ›  Nick

在javascript中使用setInterval时,请保持在类的范围内

  •  -3
  • Nick  · 技术社区  · 7 年前

    我有一个类来管理我与NodeJS中套接字的连接。每当连接无法建立或丢失时,我想设置一个间隔,以保持重试连接。然而,如果我打电话给 setInterval 函数,我作为引用传递的方法现在在 . 我的套接字类中的方法现在不再可用,除非有一些巨大的嵌套语句,否则我无法重新连接套接字。主要问题是我在 connect() 方法现在在的范围内不再可用 setInterval()

    你有什么想法可以让它工作吗?

    class SocketClass {
    
      constructor() {
        this.socket = {}
        this.port = 0
        this.host = ''
        this.intervalID = null
      }
    
    
      connect(port, host) {
        this.port = port;
        this.host = host;
        this.connectImpl()
        this.socket.on('error', () => this.errorEventHandler())
        this.socket.on('close', () => this.closeEventHandler())
      }
    
      connectEventHandler() {
        console.log('Connected!')
        if (this.intervalID !== null) {
          clearInterval(this.intervalID);
        }
      }
    
      errorEventHandler() {
        console.log('Error!')
      }
    
      connectImpl() {
        console.log('Trying to connect...')
        this.socket = require('net').Socket().connect(this.port, this.host)
      }
    
      closeEventHandler() {
        console.log('Connection lost')
        this.intervalID = setInterval(() => this.connectImpl(), 1000)
        // this.connectImpl() is called correctly but the event 
        // handlers defined in the constructor are now no longer bound
      }
    
    }
    
    export default new SocketClass
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Alnitak    7 年前

    不管你的评论怎么说,你实际上并不是在给你的朋友打电话 connectImpl

    this.intervalID = setInterval(() => this.connectImpl(), 1000)
    

    如果没有额外的paren,您只需传递一个对arrow函数的引用 连接MPL .

    connectImpl() 古老的 不是 与范围相关的问题。

    您还需要确保您致电 clearInterval(this.intervalID) closeEventHandler