简体   繁体   English

导入/导出,ES6和扩展类

[英]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. 我正在创建一个名为Carousel的类,并从该类中调用一个名为Pips的类,该类将通过父子关系绑定到该旋转木马。

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 . 显然存在循环依赖,但是当尝试将一个Class与另一个位于单独文件中的Class进行扩展时,我无法看到如何使用ES6语法避免这种情况-如果我从中删除import { Carousel }... pips.js然后我简单地得到错误,即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. 如果将“ Pips”类移动到与“ Carousel”类相同的文件中,并且在其下,则不会出现此错误,因此请认为问题可能与ES6吊装进口有关。

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. 我真的不明白为什么Pips从Carousel继承下来。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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