简体   繁体   中英

CoffeeScript - How do I retrieve a static array property in class

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM