Reputation: 5038
I just started learning CoffeeScript and I'd like to know what the best practice is for retrieving a static property in a class from a child instance.
class Mutant
MutantArray: []
constructor: (@name, @strength = 1, @agility = 1) ->
@MutantArray.push(@name)
attack: (opponent) ->
if opponent in @MutantArray then console.log @name + " is attacking " + opponent else console.log "No Mutant by the name of '" + opponent + "' found."
@getMutants: () ->
# IS THIS RIGHT?
console.log @.prototype.MutantArray
Wolverine = new Mutant("Wolverine", 1, 2)
Rogue = new Mutant("Rogue", 5, 6)
Rogue.attack("Wolverine")
Mutant.getMutants()
I would like my getMutants() method to be static (no instantiation needed) and return a list of Mutant names that have been instantiated. @.prototype.MutantArray seems to work fine, but is there a better way to do this? I tried @MutantArray but that doesn't work.
Thanks!
Upvotes: 0
Views: 78
Reputation: 3486
I think you should define your MutantArray as static field. Then, from non-static methods you should reference it via class and from static methods you access it via @. Like this:
class Mutant
@MutantArray: []
constructor: (@name, @strength = 1, @agility = 1) ->
Mutant.MutantArray.push(@name)
attack: (opponent) ->
if opponent in Mutant.MutantArray then console.log @name + " is attacking " + opponent else console.log "No Mutant by the name of '" + opponent + "' found."
@getMutants: () ->
# IS THIS RIGHT?
console.log @MutantArray
Upvotes: 1
Reputation: 292
I think it is so:
class Mutant
MutantArray: []
constructor: (@name, @strength = 1, @agility = 1) ->
@MutantArray.push(@name)
attack: (opponent) ->
if opponent in @MutantArray then console.log @name + " is attacking " + opponent else console.log "No Mutant by the name of '" + opponent + "' found."
getMutants: () ->
# IS THIS RIGHT?
console.log @.MutantArray
Wolverine = new Mutant("Wolverine", 1, 2)
Rogue = new Mutant("Rogue", 5, 6)
Rogue.attack("Wolverine")
Mutant.getMutants()
getMutants must to be a prototype method, and you retrieve the array value with @.getMutants
Upvotes: 0