ZackaryF
ZackaryF

Reputation: 39

How do I define methods in Javascript objects?

I'm new to Javascript, I'm working on a small game to get a better handle of it. I'm trying to define a character object with methods, but for some reason I'm getting weird errors from my IDE, "Label 'updateHealth' on function statement, Missing name in function declaration". I'm just trying to figure out what I'm doing wrong. In my code, display is how the character's health display's on the screen.

  function Character(display) {
    this.health = 100;
    this.display = display;


    // updates the health on the screen
    updateHealth: function() {
       if(health == 100) {
         this.display.innerText = 'HP: ' + health;
    }
    else if(health > 10 && health < 100) {
      this.display.innerText = 'HP: 0' + health;
    }
    else if(health < 10 && health > 0) {
      this.display.innerText = 'HP: 00' + health;
    }
    else {
      this.display.innerText = 'HP: 000';
    }
  }

  // returns true if character has died
  checkForDeath: function() {
    if(health <= 0) return true;
    else return false;
  }

  // function used when damage is inflicted on
  // a character object
  takeDamange: function(damage) {
    this.health -= damage;
  }

  // handles the four possible moves
  // opponent is null because if player heals
  // then it does not make sense for there to be
  // an opponent
  makeMove: function(move, opponent=null) {
    switch(move) {
      case 'PUNCH':
        opponent.takeDamage(parseInt(Math.random() * 100) % 10);
        opponent.updateHealth();
        break;
      case 'HEAL':
        this.health += 20;
        break;
      case 'KICK':
        opponent.takeDamage(parseInt(Math.random() * 100) % 20);
        opponent.updateHealth();
        break;
      case 'EXTERMINATE':
        opponent.takeDamage(opponent.health);
        opponent.updateHealth();
        break;
    }

    return opponent.checkForDeath();
  }
}

Upvotes: 0

Views: 100

Answers (3)

jhpratt
jhpratt

Reputation: 7130

I'd recommend using the class syntax.

class Character {
    constructor(display) {
        this.health = 100;
        this.display = display;
    }

    // updates the health on the screen
    updateHealth() {
        this.display.innerText = `HP: ${Math.max(health, 0).toString().padStart(3, '0')}`;
    }

    // returns true if character has died
    checkForDeath() {
        return health <= 0;
    }

    // function used when damage is inflicted on
    // a character object
    takeDamange(damage) {
        this.health -= damage;
    }

    // handles the four possible moves
    // opponent is null because if player heals
    // then it does not make sense for there to be
    // an opponent
    makeMove(move, opponent = null) {
        switch (move) {
            case 'PUNCH':
                opponent.takeDamage(parseInt(Math.random() * 100) % 10);
                opponent.updateHealth();
                break;
            case 'HEAL':
                this.health += 20;
                break;
            case 'KICK':
                opponent.takeDamage(parseInt(Math.random() * 100) % 20);
                opponent.updateHealth();
                break;
            case 'EXTERMINATE':
                opponent.takeDamage(opponent.health);
                opponent.updateHealth();
                break;
        }

        return opponent.checkForDeath();
    }
}

I also did some slight refactoring, which should make it easier to understand what is happening.

Upvotes: 0

Seth
Seth

Reputation: 1072

change : to =, and assign it to a local property, such as

this.updateHealth = function() {
   ...
}

Upvotes: 0

Dacre Denny
Dacre Denny

Reputation: 30360

Object's can be instantiated via a constructor function such as your Character() function however, you'll need to ensure object methods (such as updateHealth(), etc) are "attached" to the instance of the character object.

One way to achieve that is via the this keyword:

/* Attach the checkForDeath() function as a method of "this" Character instance */
this.checkForDeath = function() {

  /* Accessing "this" corresponds to the instance of the character object */
  if (this.health <= 0) return true;
  else return false;
}

By making these changes, checkForDeath() is now defined as a member function of the corresponding character instance. You'll need to ensure that you access fields on the instance via this, as shown on this line if(this.health <= 0) { ... }

You'll also need to ensure that you instantiate instances of Character via the new operator like this:

const characterInstance =  new Character( someElement );

Here is a revised version of your code demonstrating this approach:

function Character(display) {
  this.health = 100;
  this.display = display;

  this.updateHealth = function() {
    const health = this.health; /* Add this */
    if (this.health == 100) { 
      this.display.innerText = 'HP: ' + health;
    } else if (health > 10 && health < 100) {
      this.display.innerText = 'HP: 0' + health;
    } else if (health < 10 && health > 0) {
      this.display.innerText = 'HP: 00' + health;
    } else {
      this.display.innerText = 'HP: 000';
    }
  }
  
  this.checkForDeath = function() {
    if (this.health <= 0) return true;
    else return false;
  }

  this.takeDamange = function(damage) {
 
    this.health -= damage;
  }
  
  this.makeMove = function(move, opponent = null) {
    switch (move) {
      case 'PUNCH':
        opponent.takeDamage(parseInt(Math.random() * 100) % 10);
        opponent.updateHealth();
        break;
      case 'HEAL':
        this.health += 20;
        break;
      case 'KICK':
        opponent.takeDamage(parseInt(Math.random() * 100) % 20);
        opponent.updateHealth();
        break;
      case 'EXTERMINATE':
        opponent.takeDamage(opponent.health);
        opponent.updateHealth();
        break;
    }

    return opponent.checkForDeath();
  }
}

const player =  new Character( document.querySelector('p') );
player.takeDamange();
player.updateHealth();
<p></p>

Upvotes: 1

Related Questions