I’m trying to understand how to work with objects in javascript. The MonsterSpawn property for the Monster object is always 0 and I assume that’s because it can’t find the name array until an object is initialized? Should I instead make a method inside this object which sets the MonsterSpawn property? Is there a better way to do this? The code worked fine without using objects so it’s something I’m missunderstanding.
const Monster = {
name:[ "Ogre", "Troll", "Rat", "Goblin"],
MonsterSpawn: Math.floor(Math.random() * name.length),
MonsterHp: Math.floor(Math.random() * 99),
spawnMonster:{
}
}
>Solution :
To access the properties inside your object, you could use a getter. The getter will be able to access the properties inside its own object using this. So, if we take your code and implement a getter using the get keyword, it would be something like this:
const Monster = {
name:[ "Ogre", "Troll", "Rat", "Goblin"],
get MonsterSpawn() { return Math.floor(Math.random() * this.name.length) },
MonsterHp: Math.floor(Math.random() * 99),
spawnMonster:{
}
}
console.log(Monster);
Note that the MonsterSpawn property looks like it’s a function and you would think you have invoke it as if it’s a function, but it’s actually a property. So, accessing it, you wouldn’t invoke it like Monster.MonsterSpawn(); but call its property like Monster.MonsterSpawn; instead.