简体   繁体   English

CoffeeScript-如何在类中检索静态数组属性

[英]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. 我刚开始学习CoffeeScript,我想知道从子实例中检索类中的静态属性的最佳实践是什么。

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. 我希望我的getMutants()方法是静态的(无需实例化),并返回已实例化的Mutant名称列表。 @.prototype.MutantArray seems to work fine, but is there a better way to do this? @ .prototype.MutantArray似乎可以正常工作,但是有更好的方法吗? I tried @MutantArray but that doesn't work. 我尝试了@MutantArray,但是没有用。

Thanks! 谢谢!

I think you should define your MutantArray as static field. 我认为您应该将MutantArray定义为静态字段。 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 getMutants必须是原型方法,然后使用@ .getMutants检索数组值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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