Call a static method in the constructor - CoffeeScript

Say I declare a Game class.

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

Here I use generateNewGameId as Game.generateNewGameId() .

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

+4
source share
2 answers

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

Returns a reference to the Object function that created the instance 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 are a subclass of Game :

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

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

+13
source

I think the path you are accessing is fine. You can also do @constructor.generateNewGameId() if you don't want to write Game.generateNewGameId() for some reason, but I would prefer later. Update: as @mu is too short to mention , @constructor allows you to get an instance constructor that may be different from Game (in a subclass), so it has more flexibility; if in this case such flexibility is required, we will definitely go for it :)

If the generateNewGameId function is not accessible from outside the Game class, you can use the private function instead of the 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.

+4
source

All Articles