如何使用工厂功能解决ES6模块中的循环依赖关系? [英] How do I resolve a circular dependency in ES6 modules with a factory function?

查看:89
本文介绍了如何使用工厂功能解决ES6模块中的循环依赖关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的src/core/Chessman.js文件中写这样的东西:

I want to write something like this inside my src/core/Chessman.js file:

import King from './chessmen/King'

class Chessman {
  static factory(side, quality) {
    switch(quality) {
      case 'king' : return new King(side) break
      // ... other qualities
    }

    constructor(side) { this.side = side }

    cast(position, ref) { }

    run(position, startRef, endRef) {}
  }

并在我的src/core/chessmen/King.js文件中:

import Chessman from '../Chessman'

class King extends Chessman {

  constructor(side) {
    super(side)
    this.iterative = false // true for Queens, Rooks and Bishop
    this.directions = [
      'up', 'up+right', 'right', 'right+down', 
      'down', 'down+left', 'left', 'left+top'
    ]
  }

  // overrides parent behavior
  cast(position, ref) {}
  run(position, startRef, endRef) {}
}

但是可悲的是,我在测试过程中遇到了因果报应,茉莉花和通天塔的错误

But sadly I get the error (while testing) with Karma, jasmine and babel

TypeError:超级表达式必须为null或函数,且未定义 在src/core/chessmen/King.js:57

TypeError: Super expression must either be null or a function, not undefined at src/core/chessmen/King.js:57

King.js暂时没有第57行!

推荐答案

您有一个循环依赖项错误.根据您向我们展示的内容,请考虑以下步骤:

You have a circular dependency error. Given what you've shown us, consider the following steps:

  1. Chessman.js开始加载
  2. 它将暂停执行,以便可以加载其依赖项.
  3. King.js开始加载,因为它是依赖项.
  4. King.js抛出异常是因为class King extends Chessman运行,但是尚未设置Chessman,因为它已在步骤#2上暂停
  1. Chessman.js starts loading
  2. It pauses execution so its dependencies can load.
  3. King.js starts loading since it is a dependency.
  4. King.js throws because class King extends Chessman runs, but Chessman has not been set yet, because it paused on step #2

最好将工厂函数移动到其自己的文件中,以避免循环依赖. JS中唯一安全的循环依赖项是模块本身初始化时不需要的那些循环依赖项.由于class extends X在模块初始化时运行,因此对于周期来说是不安全的.

You'd be much better off moving your factory function to its own file, to avoid cyclical dependencies. The only safe circular dependencies in JS are ones that are not needed when the module itself is initialized. Since class extends X runs at module initialization time, it is not safe for cycles.

如果这实际上是您唯一的课程,则可以编写应用程序,以便在Chessman.js之前导入King.js,但是鉴于您使用的是工厂以及您的命名方案,我认为还有其他棋子.由于每个棋子类都会触发此问题,因此无法以正确的顺序导入它们.通过将工厂功能移出Chessman.js来避免此问题,这是唯一的解决方案.

If this was literally your only class, you could write your app such that King.js was imported before Chessman.js, but given your usage of a factory, and your naming scheme, I assume there are other chess pieces. Since every single chess piece class will trigger this issue, there is no way to import them in the correct order. Avoiding the issue by moving the factory function out of Chessman.js is the only solution to this.

这篇关于如何使用工厂功能解决ES6模块中的循环依赖关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆