我正在研究“经理”,以选择将要放置在某个地块上的农作物。每种作物都有完全不同的设计,因此它们都有自己的类/对象。但是,与其编写超过40条不同的行来实例化该类,不如我希望其中一行仅包含与类的确切名称匹配的字符串,然后运行它。这样,我的代码将保持干净。我尝试了一些东西,但从未设法完成。通常会导致以下错误:
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)
}
}
注意每种作物的类名= crop + cropname(cropCarrots,cropCows等)
重新考虑在中存储键值对的方式this.cropclasses
。现在完成的方式是将其'ActualClass'
作为键,并且'plotNameOfTheClass'
(或任何'plot' + className
产生的值)作为值,因此,当以后以数组形式访问它时,this.crop
由于'plotNameOfTheClass'
映射中没有键,因此未定义。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句