简体   繁体   中英

Imports/Exports, ES6 and Extending classes

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM