簡體   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