简体   繁体   中英

How to to export both the class and superclass in Node.js using module.exports and require()?

This may be obvious, but I do not understand how to use module.export to export both the subclass and superclass. I'm currently getting the error ReferenceError: not defined . Here's the an example subclass Dalmatian in /js/dalmatian.js :

class Dalmatian extends Dog{
  constructor(){
       super();
      /// stuff
  }
}

module.exports = {
  Dalmatian : Dalmatian
}

If I then export this class in another *.js file, I run into problems:

require('../js/dog.js');   // this works
require('../js/dalmatian.js');   // this fails

ReferenceError: Dog is not defined

I don't understand. The super constructor is used within Dalmatian, ie super(); .

How do I export the base class (which here is Dog ) so I don't get this error?

You have to require the parent class in your child class declaration. Also export the parent form subclass export clause.

You can then use both Dog and Dalmatian from your script that requires('./dalmatian') child class.

Here's a working example:

dog.js

class Dog{
    constructor(){
      console.log('dog');
  }
}

module.exports = Dog;

dalmatian.js (note how we export both)

const Dog = require('./dog');

class Dalmatian extends Dog{
    constructor(){
        super();
      console.log('dalmatian');
  }
}

module.exports = {
  Dalmatian : Dalmatian, //export this class
  Dog: Dog // and export parent class too!
}

test.js

const Dalmatian = require('./dalmatian').Dalmatian;
const Dog = require('./dalmatian').Dog; //---> Notice this
//const Dog = require('./dog'); ---> works too, but above is clearer and cleaner

new Dalmatian();
new Dog();

Output:

➔ node test.js
dog
dalmatian
dog

Dog is not defined in the module containing Dalmation , because modules don't have access to each other's variables.

Your Dalmation module should look something like this:

var parentClass = require('./Dog.js')

class Dalmatian extends parentClass.Dog {
    constructor(){
      super();
      console.log('starting dalmation')
    }
}

module.exports = {
  Dalmatian: Dalmatian
}

Also, note the super() should be called in the constructor method, not before it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM