Multiple classes in a module ok?

Posted on
  • Can you specify multiple classes in a module? If so, how do
    you reference them individually after a requires() invocation?

    --- modules/animals.js ---

    class Animal { }
    class Dog extends Animal { }
    class Cat extends Animal { }

    exports = Dog, Cat;


    var animals = require("animals");

    var d = new Dog();
    var c = new Cat();

    Uncaught ReferenceError: "Dog" is not defined
    at line 2 col 5
    var d=new Dog();

    Uncaught ReferenceError: "Cat" is not defined
    at line 3 col 5
    var c=new Cat();

  • Hi!

    You can look to the existing modules for examples.

    Particularly widget_utils maybe, then you can also look at it's corresponding tutorial.

  • Thanks!

    I actually just found the answer. You have to export your classes with names assigned:

    module.exports = {Dog: Dog, Cat: Cat};

    and then do this in your referencing code:

    var Dog = require("animals").Dog;
    var Cat = require("animals").Cat;

    var c = new Cat();

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Multiple classes in a module ok?

Posted by Avatar for MarcEvan @MarcEvan

Actions