Answer the question
In order to leave comments, you need to log in
How to create its own property using a constructor?
Hello! I'm trying to create a game. The question arose: how to correctly create a property on the player object, which will depend on the user's choice? I do it through the constructor:
function СreatePlayer(name, skills, class){
this.name = name,
this.level = 1,
this.skills = skills, this.inventory = (the value of this property
should
depend on the "class" parameter)
implement? Thanks in advance!
Answer the question
In order to leave comments, you need to log in
And class is what? If string or number - switch-case (preferably in a separate method, GetInventoryForClass). If this is a class (as an OOP unit) - then the class itself and do GetInventory. The second option is more beautiful and correct, in theory.
switch case.
The only question is where you will place it, depending on the requirements for architecture. What are class and inventory entities?
If inventory is an object, then it is logical to make a factory.
As already mentioned above, createPlayer should not be a player, but should be a factory - i.e. just create a player. something like
class BasePlayer {
}
class PlayerWithRole extends BasePlayer {
constructor(properties) {
super(properties);
}
}
let playerFactory = function (role, properties) {
let roles = {
someRole: PlayerWithRole
}
return new roles[role](properties);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question