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

标签 javascript inheritance coffeescript

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

关于javascript - CoffeeScript - 如何检索类中的静态数组属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24446376/

相关文章:

javascript - 我可以编写哪个测试来强制执行以下代码

ios - 这个地理定位计算有多准确?

javascript - 如何使用 JSDoc 记录 CoffeeScript 源代码?

javascript - 我什么时候应该写 {} 包围导入的东西?

javascript - 从另一个元素的行为更改按钮的状态

javascript - Cocos2d-js 编辑框未定义

c# - 为什么嵌套类是 "inherited"?

javascript - 概括类型化 setter 和 getter 的最佳方法是什么?

C++:这个模式有名字吗,可以改进吗?

c++ - C++ 中的继承、范围和模板构造函数