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
精彩评论