简体   繁体   中英

Strange behavior in my Hubot adapter in coffeescript on nodejs

I'm working on a Hubot adapter for my corporate chat system. The output of the following code is quite surprising, I'm not sure where to go next. There is no runtime error (as far as I can tell)

Output:

connect console
DEBUG connect logger
posted console

Code:

connect: ->
  console.log 'connect console'
  @logger.debug 'connect logger'

  @jsonClient.post 'Route/WebService/Json/Login', loginRequest, (err, res, body) ->
    console.log 'posted console'
    @logger.debug 'posted logger'

If you want @ to be the same inside the callback function as it is outside, then define the callback with a fat-arrow ( => ) :

@jsonClient.post 'Route/WebService/Json/Login', loginRequest, (err, res, body) =>
  #...

Keep in mind that @ (AKA this ) inside a (Coffee|Java)Script function depends on how the function is called, not how or where the function is defined (unless of course you have a bound function...). If you use => to define the function then it will be bound to the current @ and @logger and @jsonClient will be what you expect them to be inside the callback.

You could also use Function.bind :

callback = (err, res, body) ->
  console.log 'posted console'
  @logger.debug 'posted logger'

@jsonClient.post 'Route/WebService/Json/Login', loginRequest, callback.bind(@)

if you wanted a native solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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