我刚刚开始学习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,但这不起作用。
谢谢!
答案 0 :(得分: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
答案 1 :(得分:0)
我认为是这样的:
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
检索数组值