Phaser:通过字符串引用实例化 class
Phaser: Instantiate class by string reference
我正在研究 "manager" 以选择在特定地块上种植什么作物。每种作物都有完全不同的设计,因此有自己的 class/object。但是,与其编写 >40 行来实例化 class,我想要 1 行只包含与 class 的确切名称相匹配的字符串,然后是 运行。这样我的代码就会保持干净。我尝试了一些东西,但从未设法完成。通常会导致以下错误:
TypeError: this.crop is not a constructor
我正在尝试的代码 运行
export default class CropManager extends Phaser.Group {
constructor (game, className, plotId) {
super(game)
this.x = 0
this.y = 0
this.plotId = plotId
this.className = className
this.cropHandler(this.className)
}
// Defines which class to call
cropHandler (className) {
const ActualClass = 'plot' + className
this.cropclasses = { ActualClass: ActualClass}
this.crop = this.cropclasses[ActualClass]
this.classRun = new this.crop(this.game, this.x, this.y, this.plotId)
this.add(this.classRun)
}
}
记下每种作物的 classname = crop+cropname(cropCarrots、cropCows 等)
重新考虑在 this.cropclasses
中存储 key-value 对的方式。现在完成的方式是,它将 'ActualClass'
作为键,'plotNameOfTheClass'
(或任何 'plot' + className
产生的)作为值,因此,当稍后作为数组访问它时,this.crop
未定义,因为地图中没有 'plotNameOfTheClass'
键。
我正在研究 "manager" 以选择在特定地块上种植什么作物。每种作物都有完全不同的设计,因此有自己的 class/object。但是,与其编写 >40 行来实例化 class,我想要 1 行只包含与 class 的确切名称相匹配的字符串,然后是 运行。这样我的代码就会保持干净。我尝试了一些东西,但从未设法完成。通常会导致以下错误:
TypeError: this.crop is not a constructor
我正在尝试的代码 运行
export default class CropManager extends Phaser.Group {
constructor (game, className, plotId) {
super(game)
this.x = 0
this.y = 0
this.plotId = plotId
this.className = className
this.cropHandler(this.className)
}
// Defines which class to call
cropHandler (className) {
const ActualClass = 'plot' + className
this.cropclasses = { ActualClass: ActualClass}
this.crop = this.cropclasses[ActualClass]
this.classRun = new this.crop(this.game, this.x, this.y, this.plotId)
this.add(this.classRun)
}
}
记下每种作物的 classname = crop+cropname(cropCarrots、cropCows 等)
重新考虑在 this.cropclasses
中存储 key-value 对的方式。现在完成的方式是,它将 'ActualClass'
作为键,'plotNameOfTheClass'
(或任何 'plot' + className
产生的)作为值,因此,当稍后作为数组访问它时,this.crop
未定义,因为地图中没有 'plotNameOfTheClass'
键。