Call static method in constructor — CoffeeScript

class, coffeescript, static

Solution

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/

Problem

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.

Original source