装饰器:初始化前无法访问“ xxx”

我不确定如何解决此问题,但是出现一条错误消息:

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

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

库的主要入口点看起来像这样:

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)
lysoft11 回答:装饰器:初始化前无法访问“ xxx”

所以...看来,要执行此操作,我需要使用动态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'
本文链接:https://www.f2er.com/2462788.html

大家都在问