javascriptconstructornon-static

Why can't I call a static method from the constructor?


I'm getting into ES6 and trying to turn a class that's over 2700 lines long into a collection of small, easy-to-read files.

I'd like to move some initialization code from the constructor into their own methods. But I'm a bit stuck. Consider this code:

export default class Thingy {
  non_static_prop;

  initNonStaticStuff() {
  }

  constructor(args) {
    this.non_static_prop = 'some non-static prop set by the constructor'; // ok
    console.log(this.non_static_prop); // works as expected
    // now can we get a method to do the same thing?
    initNonStaticStuff(); // fails:
      /**
       * `Uncaught ReferenceError: initNonStaticStuff is not defined`
       */
    // So I guess we'll have to initialize everything here.
    // But then how am I supposed to make my code smaller and more modular?
  }
}

I'm confused. What options do I have to run code from the constructor?

I could, of course, call a static method instead, but then this wouldn't let me access non-static properties.

Another option I see is to ask the page that creates the instance to then run initNonStaticStuff() (e.g. say by way of a start() method), but I'd rather skip such a step if possible.

What did I miss?


Solution

  • Just call it with this.initNonStaticStuff();