Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoffeeScript and NodeJS: How do I export multiple classes?

I want to export some classes, say, Dog and Cat. One way to go about this is:

class Dog
  bark: -> console.log "Arff! :D"

class Cat
  meaow: -> console.log "Meaw!"


module.exports = {Dog, Cat}

How can I do something similar without typing the class names twice?

like image 877
Andres Riofrio Avatar asked Jun 21 '12 05:06

Andres Riofrio


2 Answers

You could use something like this:

class exports.Dog
  bark: -> console.log "Arff! :D"

This compiles down to:

exports.Dog = (function() {

  function Dog() {}

  Dog.prototype.bark = function() {
    return console.log("Arff! :D");
  };

  return Dog;

})();
like image 198
jimr Avatar answered Sep 20 '22 16:09

jimr


An alternative way to this is by doing the following:

module.exports = 
   Dog: class Dog
          bark: -> console.log "Arff! :D"

   Cat: class Cat
         meaow: -> console.log "Meaw!"

Then you can do the following:

animals = require './animals'

dog = new Animals.dog()
like image 35
Menztrual Avatar answered Sep 22 '22 16:09

Menztrual