Search code examples
javascriptnode.jscoffeescript

Inheritance of a child class placed in another file (CoffeeScript)


How to organize properly child classes in different files with CoffeeScript? Here is a simple example of the problems with the code. The Snake runs just fine, but then trying to use the Dog class (because it is placed in another class), it gives the following error:

TypeError: Dog is not a constructor

Main file: .test/Animals.coffee

#expect = require "expect.js"
Animal = require "../learning/Animals"
Snake = Animal.Snake
Dog = require "../learning/Dog"
#Dog = Animal.Dog #unresolved variable

describe 'animals', ->
  it 'test inheritance', ->
    sam = new Snake "Sammy the Python"
    peanut = new Dog "Peanut the Dog"

    sam.move()
    peanut.move()

Parent class: .learning/Animals.coffee

class Animal
  constructor: (@name) ->

  move: (meters) ->
    console.log(@name + " moved #{meters}m.")

class Snake extends Animal
  move: ->
    console.log( "Slithering...")
    super 5

module.exports = { Animal, Snake }

Child class: .learning/Dog.coffee

Animal = require './Animals'

class Dog extends Animal
  move: ->
    console.log( "Runs...")
    super 15

module.exports = { Dog }

Solution

  • You are exporting objects containing classes:

    module.exports = { Dog }
    

    This is equivalent to

    module.exports = {
      Dog: Dog
    }
    

    You can destructure the imported object:

    { Dog } = require('./Dog.coffee')
    

    This is similar to:

    a = require('./Dog.coffee')
    Dog = a.Dog
    

    You should be consistent and always export objects, and always destructure the imported object into those parts which you need.

    Alternatively, I would suggest giving each class it's own file to avoid confusion