Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Deleting objects/overwriting them?

Hey guys,

I posted the other day with this "RPG" project I was doing to try to practice objects. I have changed my approach but I still haven't managed to get it working. The full code is here:

http://codepen.io/swhizzle/pen/mJyrXr

The idea is really simple, the user clicks the "New Battle" button and this generates a random monster (see newMonsterCall();) with random statistics (see getRandomizer();). Then when the user clicks "attack" it will simply subtract the player object's attack power against the random monster's hit points and append this to the #battleField element.

The problem I am having is the previous objects are not being overwritten properly when I call the newMonsterCall() function. Therefore, I have tried to "delete" the previous instances by using:

 for (item in monsterObject) {
    delete monsterObject[item]
}

This solves the problem EXCEPT the battle text starts saying "You hit UNDEFINED for 5 damage", Is there any way I can completely delete all references to an object in Javascript? Or at least overwrite them?

I've been trying to get this to work for about 15 hours now, I really would like some help.. ha..

1 Answer

I have actually fixed the problem of it showing "You have hit undefined" by making a function:

    function badNameFix() {
        if (typeof monsterObject.monsterName == "string") {
            return '<p>You attack the '+monsterObject.monsterName+' for '+player1.attPower+' damage</p>';
        } else {
            return null;
        }

But I know for a fact this can't be the best solution to my problem. Any other ideas?