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