Gautham Badhrinathan
Gautham Badhrinathan

Reputation: 2437

Call static method in constructor — CoffeeScript

Say I'm declaring a class Game.

class @Game
    constructor: ->
        @id = Game.generateNewGameId() # <---
    player1: null
    player2: null
    @generateNewGameId: -> "blahblah23"

Here, I'm using generateNewGameId as Game.generateNewGameId().

Is this the right way or is there a better way? I've tried using this::generateNewGameId() but the scope's different.

Upvotes: 4

Views: 3556

Answers (2)

mu is too short
mu is too short

Reputation: 434685

If you really want generateNewGameId to be a class method then you can use @constructor to get at it:

Returns a reference to the Object function that created the instance's prototype. Note that the value of this property is a reference to the function itself [...]

So something like this:

class Game
    constructor: ->
        @id = @constructor.generateNewGameId()
    @generateNewGameId: ->
        "blahblah23"

Note that this will do The Right Thing if you subclass Game:

class C extends Game # With an override of the class method
    @generateNewGameId: ->
        'pancakes'    

class C2 extends Game # or without

Demo (open your console please): http://jsfiddle.net/ambiguous/Vz2SE/

Upvotes: 13

epidemian
epidemian

Reputation: 19219

I think the way you are accessing it is OK. You can also do @constructor.generateNewGameId() if you don't want to write Game.generateNewGameId() for some reason, but i'd prefer the later. Update: as @mu is too short mentions, the @constructor allows you to get the constructor of the instance, which can be differ from Game (in a subclass) so it has greater flexibility; if that flexibility is required in this case, definitely go for that :)

If the generateNewGameId function will not be accessed from outside the Game class, you can use a private function instead of a class method:

class @Game
  gameIdCounter = 0
  generateNewGameId = -> gameIdCounter++
  constructor: ->
    @id = generateNewGameId()
  player1: null
  player2: null

console.log (new Game).id # -> 0
console.log (new Game).id # -> 1

Example at coffeescript.org.

There both gameIdCounter and generateNewGameId are private variables inside the Game class.

Upvotes: 4

Related Questions