【问题标题】:Decorator: Cannot access 'xxx' before initialization装饰器:初始化前无法访问“xxx”
【发布时间】:2020-04-11 17:44:41
【问题描述】:

我不知道如何解决这个问题,但我收到一条错误消息:

未捕获的 ReferenceError:在初始化之前无法访问“游戏”

所以,我尝试将属性和方法设为静态,但没有做任何事情。我该怎么做才能将装饰器添加到将项目添加到 Game 类中的 registeredComponents 属性的类中?

库主入口点如下所示:

import { Game } from './Game'
export const game = new Game

游戏组件创建一个 Transform 实例并将其添加到其内部列表中:

import { Transform } from './core/components/Transform'

export class Game {
  private registeredComponents: Set<typeof Behavior> = new Set<typeof Behavior>()

  public registerComponent(component: typeof Behavior): void {
    this.registeredComponents.add(component)
  }

  public instantiate() {
    const gameObject = new GameObject()
    const transform = new Transform(gameObject)
    // Do some other stuff
  }
}

这里我在 Transform 上使用了我的装饰器:

@Component()
export class Transform extends Behavior {
  public position: Vector3 = Vector3.zero
}

这就是装饰器的样子:

export function Component() {
  return (target: typeof Behavior): void => {
    game.registerComponent(target)
  }
}

用法

在我用来使用这个库的另一个项目中,它看起来像这样:

import { game, PrefabUtil } from 'gameengine'

class Item extends PrefabUtil { }

game.instantiate(Item)

【问题讨论】:

  • 存在循环依赖索引->游戏->变换->组件->游戏
  • 这不是循环依赖,除非游戏被导出到它不是的组件中。
  • 是的。您的装饰器使用 Game 的一个实例。游戏类使用用上述装饰器装饰的 Transform 类。装饰器适用于评估模块时(导入时)而不是创建实例时(new Transform())
  • @Shlang,实际上这是真的,但很好。正如您所说,在评估模块时会调用装饰器,但抛出的不是装饰器,而是它返回的函数。
  • function Component 不是装饰器,它是一个装饰器工厂(因此你需要在应用它时添加()),它返回的函数是一个真正的装饰器,当模块调用被评估。请查看this playground

标签: javascript typescript typescript-decorator


【解决方案1】:

所以...看起来为了做到这一点,我需要使用动态import()。这将延迟对装饰器的调用,直到创建 Game 对象之后。

export class Game {
  public async instantiate() {
    const Transform = (await import('./core/components/Transform')).Transform
    const transform = new Transform(gameObject)
  }
}

还需要删除以下行:

import { Transform } from './core/components/Transform'

【讨论】:

  • 在这种情况下,Javascript 的灵活性可能会受到负面影响。您的错误是由@Shlang 提到的循环依赖引起的,并且存在循环依赖表明您的架构存在问题。您已经找到了一个 hacky 解决方案,可以让它按您想要的方式运行,但它可能会让您日后无休止的悲伤。请再看一遍,看看您是否可以以不同的方式构建代码,以在没有 hack 的情况下仍然实现您想要的,从长远来看,它会为您节省大量时间和问题!
猜你喜欢
  • 1970-01-01
  • 2023-04-08
  • 2020-08-25
  • 2020-09-08
  • 2021-09-29
  • 2019-10-12
  • 2020-11-30
  • 2021-11-02
  • 2022-01-04
相关资源
最近更新 更多