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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With