开发者

Iterate through a list of objects in coffeescript

I have code like this:

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

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

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

What I want is something like this:

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

but it doesn't work that way. 开发者_运维百科Is it possible to iterate through a list of objects with the same structure?


Did you mean:

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()

(changing new Animal to new Canine)? Because that works fine... I get the expected output

poodle
labrador
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜