CoffeeScript类 - 循环继承对象的数组

时间:2012-03-26 16:55:56

标签: javascript coffeescript prototype

我有以下coffeescript:

class Vehicles
  constructor: (@name) ->

class Car extends Vehicles
  setId: (@id) ->
  setName: (@name) ->

class Truck extends Vehicles
  setId: (@id) ->
  setName: (@name) ->

m3 = new Car
m3.setId 2
m3.setName 'BMW M3'

m5 = new Car
m5.setId 4
m5.setName 'BMW M5'

'Car'对象将从一组数据动态生成。

在Vehicles类中,我如何遍历所有Car对象并访问每个单独的属性?

谢谢!

1 个答案:

答案 0 :(得分:2)

与Ruby不同,CoffeeScript在实例化类时不会运行任何幕后代码;您需要使用Car构造函数添加您自己谈论的功能。因此,例如,要将所有汽车的列表维护为Vehicles.cars,您可以写:

class Vehicles
  @cars = []
  constructor: (@name) ->

class Car extends Vehicles
  constructor: ->
    Vehicles.cars.push @
  setId: (@id) ->
  setName: (@name) ->

迭代它们并显示它们的所有属性:

console.log(car.id, car.name) for car in Vehicles.cars