Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

javascript - Can you export multiple classes from a single Nodejs Module?

Currently, I have 4 Child Classes each in their own file. I'm requiring them all in the same file. I am wondering if I can contain all 4 of those classes in a single module. Currently, I'm importing them like this

var Jack = require('./Jack.js');
var JackInstance = new Jack();
var Jones = require('./Jones.js');
var JonesInstance = new Jones();

I'd like to import them like this

var People = require('./People.js');
var JackInstance = new People.Jack();

Or even

var Jack = require('./People.js').Jack;
var JackInstance = new Jack();

My classes are defined like so

class Jack{
    //Memeber variables, functions, etc
}

module.exports = Jack;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can export multiple classes like this:

e.g. People.js

class Jack{
   //Member variables, functions, etc
}

class John{
   //Member variables, functions, etc
}

module.exports = {
  Jack : Jack,
  John : John
}

And access these classes as you have correctly mentioned:

var People = require('./People.js');
var JackInstance = new People.Jack();
var JohnInstance = new People.John();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...