K
K
Kirill Gostiev2016-02-17 13:50:12
JavaScript
Kirill Gostiev, 2016-02-17 13:50:12

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

3 answer(s)
G
GavriKos, 2016-02-17
@auramaker

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.

A
Andrey Sedyshev, 2016-02-17
@ musikant777

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.

A
Anton, 2016-02-17
@SPAHI4

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 question

Ask a Question

731 491 924 answers to any question