Splitting node.js class extensions between files

126 Views Asked by At

I am trying to make a discord bot in node.js. I have a main file, bot.js, which contains the main control flow. I would like to implement the state of the world as a class and split the actions on that class into other files. However, I'm not really sure how to do this, particularly the part where I have to recombine multiple files of functions (let's call them startup.js and bios.js) that extend the same class.

Should I have a separate file that includes the class definition so that I can import that into both of the helper files?

common.js

module.exports = botState;

class botState {
    //class definition goes here
}

initialize.js

const common = require('./common');

class initializeState extends botState {
    constructor () {
        //it's a constructor; details not too important
    }

    function1 () {} //implementation not important

    function2 () {}
}

module.exports = initializeState;

chars.js

const common = require('./common');

class bioState extends botState {
    constructor () {
        //it's a constructor; details not too important
    }

    function3 () {} //implementation not important

    function4 () {}
}

module.exports = BioState;

bot.js

//main control flow is in this file
//I'd like to have a class that implements functions 1 through 4, but don't know how to do that.

I'm not sure how to implement bot.js. There might be some better construction for this entirely.

1

There are 1 best solutions below

3
David Sampson On

It sounds like you are trying to do some multiple inheritance, which isn't supported in Javascript (see the last section here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model), either in the same file or in different files.

That said, what you can do is take advantage of how the prototyping system works. You can write functions 1-4 separately from the class definitions, and attach them to the prototypes of the classes you want.

function function1(){
  this.someValue = this.someOtherValue + this.someMethod();
  return 7;
}
// ... and other functions

BioState.prototype.function1 = function1;
InitializeState.prototype.function1 = function1;

It doesn't matter where these are defined or attached to the class prototypes -- though for clarity's sake it would make sense to declare the functions in one place, import them to the file for each class that needs it, and attach them to the prototype before you export the class.

const { function1, function2 } = require('./common-functions');
class Blah {
//...
}
Blah.prototype.function1 = function1;
Blah.prototype.function2 = function2;
// You could also do this in the constructor as this.function1 = function1;

module.exports = Blah;