我有这样的代码:
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()
但它不起作用。 是否可以迭代具有相同结构的对象列表?
答案 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