【问题标题】:CoffeeScript - How do I retrieve a static array property in classCoffeeScript - 如何在类中检索静态数组属性
【发布时间】:2014-08-18 05:48:45
【问题描述】:

我刚开始学习 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,但这不起作用。

谢谢!

【问题讨论】:

    标签: javascript inheritance coffeescript


    【解决方案1】:

    我认为您应该将 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
    

    【讨论】:

      【解决方案2】:

      我认为是这样的:

      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 检索数组值

      【讨论】:

        猜你喜欢
        • 2020-02-15
        • 1970-01-01
        • 2017-11-02
        • 2021-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多