【发布时间】: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