dzm
dzm

Reputation: 23534

CoffeeScript classes - loop through array of inherited objects

I have the following 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'

The 'Car' objects will be generated dynamically from an array of data.

In the Vehicles class, how would I loop through all Car objects and access each individual property?

Thank you!

Upvotes: 1

Views: 354

Answers (1)

Trevor Burnham
Trevor Burnham

Reputation: 77416

Unlike Ruby, CoffeeScript doesn't run any behind-the-scenes code when you instantiate a class; you need to add the functionality you're talking about yourself, using the Car constructor. So, for instance, to maintain a list of all cars as Vehicles.cars, you would write:

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

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

To iterate through them and show all their properties:

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

Upvotes: 2

Related Questions