Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 426
Gautham Badhrinathan Avatar asked Dec 04 '22 02:12

Gautham Badhrinathan


1 Answers

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/

like image 188
mu is too short Avatar answered Dec 22 '22 00:12

mu is too short