Reputation: 634
I am working on a "manager" for selecting what crop shall be placed on a certain plot. Every crop has a completely different design and therefor their own class/object. However instead of writting >40 different lines that will instantiate that class I would like 1 line that simply contains the string that matches the exact name of a class and then run it. That way my code will stay clean. I have tried some stuff but never managed to get it done. Usually resulting in an the following error:
TypeError: this.crop is not a constructor
The code I am attempting to run
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)
}
}
Note every crop their classname = crop+cropname (cropCarrots, cropCows, etc)
Upvotes: 3
Views: 90
Reputation: 3747
Rethink the way you're storing key-value pairs in this.cropclasses
. The way it's done now, it's going to have 'ActualClass'
as the key and 'plotNameOfTheClass'
(or whatever 'plot' + className
produces) as the value, thus, when accessing it later as an array, this.crop
comes out undefined since there isn't a 'plotNameOfTheClass'
key in the map.
Upvotes: 2