Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coffeescript/Javascript variable scope

I'm not really sure why i do not have access to the @date (this.date) variable from the context of the anonymous function defined in C.f()

class C
  constructor: () ->
    @date = new Date()

  f: () ->
    $(document).keydown( (e) ->
      alert(@date)
    )

Could someone comment on that?

like image 579
Juliusz Avatar asked Aug 15 '11 06:08

Juliusz


People also ask

Is CoffeeScript obsolete?

As of today, January 2020, CoffeeScript is completely dead on the market (though the GitHub repository is still kind of alive).

Is CoffeeScript slower than JavaScript?

Short answer: No. CoffeeScript generates javascript, so its maximum possible speed equals to the speed of javascript.


1 Answers

This is happening because inside the keydown event handler, the this value will not refer to your object, it will refer to the DOM element.

For that purpose, you can use => (the fat arrow), that will bind the handler's this value to the parent this:

class C
  constructor: () ->
    @date = new Date()

  f: () ->
    $(document).keydown( (e) =>
      alert(@date)
    )
like image 63
Christian C. Salvadó Avatar answered Oct 13 '22 10:10

Christian C. Salvadó