How can I resolve a circular dependency between different ECMAScript modules?

670 views Asked by At

I am creating a class called Carousel and from within that class want to call a class called Pips that will be tied to the carousel through a parent-child relationship.

The problem I have is that I am receiving the following error:

Super expression must either be null or a function, not undefined

My current code looks like this:

// carousel.js

import { Pips } from './pips'

export class Carousel {
  constructor( options ) {
    this.pip_type = options.pip_type;
  }

  setup() {
    this.initPips();
  }

  initPips() {
    var p = new Pips(
      { 
        carousel_name : 'carousel',
        pip_type      : this.pip_type
      }
    );
  }
}


// pips.js

import { Carousel } from './carousel'

export class Pips extends Carousel {
  constructor(options) {
    super(options);
    console.log( 'Pips Initialised' );
  }
  
}

It is clear that there is a circular dependency going on but I can't see how to avoid that with ES6 syntax when trying to extend one Class with another that sits in a separate file - if I remove import { Carousel }... from pips.js then I simply get the error that Carousel is undefined.

If I move the Pips Class to be in the same file as my Carousel class and beneath it then I don't get this error so think the problem might be to do with ES6 hoisting imports.

What would be the best way for me to establish this relationship between these two classes?

1

There are 1 answers

0
chrilith On

This is more a design problem in your class hierarchy. The super class should not be aware of and/or use reference to subclasses.

Check here for details

Perhaps you should go with composition instead of trying to do circular references.

I don't really see why Pips inherit from Carousel.

Hope this helps.