How to add onto a class after its definition?

Viewed 53

I have a big class, called game, and it has many nested classes and functions.

class Game {
  constructor(opts) {

    this.Thing = class {
      constructor() {
        //do stuff
      }
      //a ton of functions
    }
    //a ton of functions

  }
}

I would like a way to organize it and make it easier to develop.

I was thinking of splitting the class up into multiple files, but I don't know how that would work.

Is there any way for me split this class up into multiple files? If not how else can I organize it, is there a better way?

1 Answers

One way to make this less verbose is to define some (or all) of the functions within other files. Just make sure you use the function keyword instead of an arrow function so that when you reference this, you're referencing the class it eventually gets put into. For instance, you can do something like this in one file:

export function method() {}

and then include it like this in your main file:

import { method } from './method';

class BigClass {
  constructor() {}

  method = method
}

Any reference to this within the method will refer to the instance it's called on.

As for nested classes, you should just be able to export the class from another file like so:

export class OtherClass {
   constructor() {}
}
import { OtherClass } from './otherclass'

class BigClass {
  constructor() {}

  OtherClass = OtherClass;
}
Related