Last Updated: February 25, 2016
· jodosha
Avatar white

Constants in CoffeeScript

If you want to avoid magic numbers, one good practice is to use constants, here my solution with CoffeeScript:

class FormValidator

  validate: ( ) ->
    if @input.val() == @CREDIT_CARD
      # ...

2 Responses
Add your response


This would add them to the prototype. In case you'd need to access it from outside the methods of the class, you would do it through the instance, which is counter-intuitive in most languages.

Another way to go is:

class FormValidator
  @CREDIT_CARD: '1'  # or @CREDIT_CARD = '1', generates the same thing

  show: ( ) ->
    if @input.val() == @constructor.CREDIT_CARD

That way the constant is tied to the constructor, not the prototype. And it's accessible from outside with FormValidation.CREDIT_CARD, kinda the way you'd expect a Ruby constant to be.

Another alternative is:

class FormValidator

  validate: ( ) ->
    if @input.val() == CREDIT_CARD

Coffeescript will do a var CREDIT_CARD = '1' inside the scope of the FormVaildator definition, so CREDIT_CARD will only be accessible from the classes methods, and not made public through the instances.

over 1 year ago ·
Avatar white

Thanks for the clarification. Was this syntax introduced recently? IIRC, my first attempt was written like your last example, but it didn't worked.

over 1 year ago ·