迭代coffeescript中的对象列表

时间:2011-08-07 06:21:54

标签: coffeescript

我有这样的代码:

class Canine
  constructor: (@breed) ->
  whichBreed: ->
    alert @breed

poodle = new Canine "poodle"
labrador = new Canine "labrador"

iterate = ->
  poodle.whichBreed()
  labrador.whichBreed()

我想要的是这样的:

listOfDogs = [poodle, labrador]
for d in listOfDogs
  d.whichBreed()

但它不起作用。 是否可以迭代具有相同结构的对象列表?

1 个答案:

答案 0 :(得分:2)

你的意思是:

class Canine
  constructor: (@breed) ->
  whichBreed: ->
    alert @breed

poodle = new Canine "poodle"
labrador = new Canine "labrador"

iterate = ->
  poodle.whichBreed()
  labrador.whichBreed()

listOfDogs = [poodle, labrador]
for d in listOfDogs
  d.whichBreed()

(将new Animal更改为new Canine)?因为这很好......我得到了预期的输出

poodle
labrador