Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Do I need to make a method in an object to call it's own properties?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading