JavaScript Classes: Understanding Methods, Objects, and Their Interactions

Class Structure in JavaScript

JavaScript classes provide a blueprint for creating objects. They encapsulate properties (attributes) and methods (functions) to define the behavior of an object.

A typical class definition includes:

  • A constructor for initializing objects
  • Methods for defining behavior
  • Properties to store data

Example Class from PBL Code

Consider the PlayerForBattle class used in my PBL project:

class PlayerForBattle {
    constructor(name, health, attack) {
        this.name = name;
        this.health = health;
        this.attack = attack;
    }

    takeDamage(amount) {
        this.health -= amount;
        console.log(`${this.name} took ${amount} damage. Health left: ${this.health}`);
    }

    attackEnemy(enemy) {
        enemy.takeDamage(this.attack);
        console.log(`${this.name} attacked ${enemy.name} for ${this.attack} damage.`);
    }
}

Instantiating and Using Objects

To create and use objects, I instantiate the class using the new keyword:

let player1 = new PlayerForBattle("Hero", 100, 15);
let player2 = new PlayerForBattle("Villain", 80, 12);

Once instantiated, I can use the class methods:

player1.attackEnemy(player2); // Hero attacks Villain
player2.takeDamage(15); // Villain takes 15 damage

Calling Methods and Handling Parameters

Methods in classes allow objects to interact. In the attackEnemy method:

attackEnemy(enemy) {
    enemy.takeDamage(this.attack);
    console.log(`${this.name} attacked ${enemy.name} for ${this.attack} damage.`);
}
  • enemy is a parameter that represents another object.
  • The method calls enemy.takeDamage(this.attack), modifying the enemy’s state.

Return Values in Methods

Methods can return values instead of just printing output. Example:

getHealthStatus() {
    return `${this.name} has ${this.health} health left.`;
}

Usage:

console.log(player1.getHealthStatus());

Draw.io Diagram Representation

A Draw.io (diagrams.net) diagram can visually represent the relationships in our class.

  • Class: PlayerForBattle
  • Attributes: name, health, attack
  • Methods: takeDamage(), attackEnemy(), getHealthStatus()
  • Arrows: Show method interactions between objects