繁体   English   中英

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

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

我刚开始学习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()

我希望我的getMutants()方法是静态的(无需实例化),并返回已实例化的Mutant名称列表。 @ .prototype.MutantArray似乎可以正常工作,但是有更好的方法吗? 我尝试了@MutantArray,但是没有用。

谢谢!

我认为您应该将MutantArray定义为静态字段。 然后,从非静态方法中,您应该通过类对其进行引用,而从静态方法中,则应通过@访问它。 像这样:

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

我认为是这样的:

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必须是原型方法,然后使用@ .getMutants检索数组值

暂无
暂无

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

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