Javascript 如何在发出的事件调用函数之外调用函数

Javascript 如何在发出的事件调用函数之外调用函数,javascript,node.js,Javascript,Node.js,我很抱歉,如果这是不清楚,它的迟到,我不知道如何最好地解释它 我使用事件发射器将数据从服务器响应传递到另一个文件中单独类内的函数,但是当尝试在这些类中使用方法时,this关键字显然不起作用(因为在这种情况下,this指的是服务器事件发射器)-如何在类本身中引用函数?我提供了一些代码来帮助更好地说明我的观点 ServiceClass.js class StreamService { /** * * @param {} database * @param {Coll

我很抱歉,如果这是不清楚,它的迟到,我不知道如何最好地解释它

我使用事件发射器将数据从服务器响应传递到另一个文件中单独类内的函数,但是当尝试在这些类中使用方法时,
this
关键字显然不起作用(因为在这种情况下,
this
指的是服务器事件发射器)-如何在类本身中引用函数?我提供了一些代码来帮助更好地说明我的观点

ServiceClass.js

class StreamService {
  /**
     *
     * @param {} database
     * @param {Collection<Guild>} guilds
  */
  constructor (database, guilds,) {
      .....
      twitchListener.on('live', this.sendLiveAlert) // fire test method when we get a notification
      // if there are streamers to monitor, being monitoring
      winston.info('Stream service initialized')
  }

  ..............

  async get (url, params = null, headers = this.defaultHeaders) {
    // check oauth token
    const expirationDate = this.token.expires_in || 0
    if (expirationDate <= Date.now() || !this.token) await this.getAccessToken()
    // build URL
    const index = 0
    let paramsString = ''
    for (const [key, value] of params.entries()) {
      if (index === 0) {
        paramsString += `?${key}=${value}`
      } else {
        paramsString += `&${key}=${value}`
      }
    }
    const res = await fetch(url + paramsString, { method: 'GET', headers: headers })
    if (!res.ok) {
      winston.error(`Error performing GET request to ${url}`)
      return null
    }
    return await res.json()
  }

  async sendLiveAlert(streamTitle, streamURL, avatar, userName, gameId, viewerCount, thumbnail, startDateTime) {
    // get game name first (no headers needed)
    const params = new Map()
    params.set('id', gameId)
    const gameData = await this.get('https://api.twitch.tv/heliix/games', params, this.defaultHeaders)
    if(gameData) {
      // get webhook and send message to channel
      const webhookClient = new WebhookClient('755641606555697305', 'OWZvI01kUUf4AAIR9uv2z4CxRse3Ik8b0LKOluaOYKmhE33h0ypMLT0JJm3laomlZ05o')
      const embed = new MessageEmbed()
        .setTitle(`${userName} just went live on Twitch!`)
        .setURL(streamURL)
        .setThumbnail(avatar)
        .addFields(
          { name: 'Now Playing', value: gameData.data[0].name },
          { name: 'Stream Title', value: streamTitle }
        )
        .setImage(thumbnail)
    }
    webhookClient.send('Webhook test', embed)
  }
}
sendLiveAlert
方法中,我试图调用StreamService类的get方法-但是因为它是通过
server.js
中的发射器直接调用的,
这个
特别指的是
server.js
类-我有没有办法使用
StreamService.get()
?很明显,我可以在方法本身内部重写代码,但如果它就在那里,这似乎是不必要的?

更改此选项:

twitchListener.on('live', this.sendLiveAlert)
为此:

twitchListener.on('live', this.sendLiveAlert.bind(this))
或者,您也可以这样做:

twitchListener.on('live', (...args) => {
    this.sendLiveAlert(...args);
});

使用
.bind()
它会创建一个函数包装器,为您重置
this
的正确值。对于箭头函数,它为您保留
this
的词法值。

同时回答。如果你在第二个选项函数中处理
args
,我可以删除我的。@RahulBhobe-我在args中添加了。这是我的想象还是答案中代码块和文本之间的边距突然增加了?啊,我明白了!我认为这是一个范围问题,我只是不知道如何处理它。这很有魅力!
twitchListener.on('live', (...args) => {
    this.sendLiveAlert(...args);
});