Search code examples
javascriptcoffeescriptthisproject-structuring

Structuring Coffeescript and using the @ keyword


This is probably very basic stuff but I'm stuck and a bit clueless.

I wrote a Snake game recently in CoffeeScript, but I'm not at all happy with the way I structured the code.

I'm trying to rewrite this using classes. I have a Game class, a Snake class, a Food class. It makes sense in my head to do it this way. However, to access variables and functions, I'm using the '@' (this) keyword, and I feel like I'm completely overdoing it. For example, I have a list of constants at the top of my Game class. I had to declare all of them as @CONSTANT to be able to access them. Or, inside of a method:

clearCanvas: ->
    @ctx.clearRect 0, 0, @canvas.width, @canvas.height

The same goes for method calls. For example:

init: ->
    window.snake = new Snake()
    @showStartScreen()

Can someone tell me if this is okay to do, or how I should structure my code? I can put a link up to the code I'm working with at the moment, if someone would be so kind to review it for me. (Edit: actually here it is)

Thanks a lot.


Solution

  • If you're using CoffeeScript classes you'll be making heavy use of @. Any properties on your objects must be accessed through @ or this. Here's how you should be using constants:

    class Game
      up:     1
      right:  2
      down:   4
      left:   8
    
      someMethod: ->
        console.log @up, @right, @down, @left
    
    console.log "Class accessible #{Game::up}"
    
    g = new Game
    console.log "Object accessinble #{g.up}"
    
    g.someMethod()
    

    Also, @thejh is right. You should be using soft tabs at 2 space width.