1

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!

0

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.