Greetings! Today, we're revisiting JavaScript classes, the core building block of Object-Oriented Programming (OOP) in JavaScript. Through hands-on examples, we'll revisit the fundamental concepts of JavaScript classes, including their structure, properties, and methods.
Let's begin with a refresher on JavaScript classes. Essential to OOP, JavaScript classes bundle relevant data and functions into compact units called objects. Consider a video game character, which is a typical example of a class instance, with specific properties (such as health
or strength
) and methods (such as attack
or defense
).
JavaScript1class GameCharacter { 2 // constructor method 3 constructor(name, health, strength) { 4 this.name = name; // property 5 this.health = health; // property 6 this.strength = strength; // property 7 } 8 9 attack(otherCharacter) { // method 10 otherCharacter.health -= this.strength; 11 } 12}
JavaScript classes facilitate the grouping of associated code elements, simplifying their management. Now, to better remind ourselves how the above example works, let's go through it step-by-step.
A JavaScript class serves as a blueprint consisting of properties and methods. While properties represent data relevant to a class instance, methods are actions or functions that manipulate this data. Each class includes a constructor
function, which is used to define class properties.
An essential keyword within these methods is this
, which represents the class instance. In object-oriented programming, it's needed to access the class's properties and methods. When a new class instance is created, JavaScript automatically passes it to the this
parameter to access individual instance properties and methods using the this
keyword. This mechanism allows each object to keep track of its own state and behaviors.
JavaScript1class GameCharacter { 2 // constructor: defines class properties 3 constructor(name, health, strength) { 4 this.name = name; // property 5 this.health = health; // property 6 this.strength = strength; // property 7 } 8} 9 10const character = new GameCharacter("Hero", 100, 20); // object or instance of the class
Properties in JavaScript classes hold data associated with each class instance. For example, in our GameCharacter
class, name
, health
, and strength
are properties. You can access a class property using the object of the class, followed by a dot (.
), and then the property name.
JavaScript1class GameCharacter { 2 // constructor: defines class properties 3 constructor(name, health, strength) { 4 this.name = name; // property 5 this.health = health; // property 6 this.strength = strength; // property 7 } 8} 9 10const character = new GameCharacter("Hero", 100, 20); // object or instance of the class 11console.log(character.name); // prints: Hero 12console.log(character.health); // prints: 100 13console.log(character.strength); // prints: 20
Properties differentiate one class instance from another and store the state of the instance.
A class also contains methods — actions or functions that manipulate the data in the class. For example, the attack
method in our GameCharacter
class simulates an attack by one game character on another.
JavaScript1class GameCharacter { 2 // constructor: defines class properties 3 constructor(name, health, strength) { 4 this.name = name; // property 5 this.health = health; // property 6 this.strength = strength; // property 7 } 8 9 attack(otherCharacter) { // method 10 otherCharacter.health -= this.strength; // modifies 'otherCharacter's health property 11 } 12} 13 14const character1 = new GameCharacter("Hero", 100, 20); // First instance of GameCharacter 15const character2 = new GameCharacter("Villain", 80, 15); // Second instance 16 17console.log(character2.health); // prints: 80 18character1.attack(character2); // character1 attacks character2 19console.log(character2.health); // prints: 60
To deepen our understanding of JavaScript classes, let's explore another example where we build a basic BankAccount
class. This class will demonstrate how we can model real-world entities using object-oriented programming by defining properties like the account holder's name and balance, and methods for depositing and withdrawing money.
JavaScript1// Define the BankAccount class 2class BankAccount { 3 // Constructor with a default balance of 0 4 constructor(holderName, balance = 0) { 5 this.holderName = holderName; 6 this.balance = balance; 7 } 8 9 // Method to deposit money 10 deposit(amount) { 11 if (amount > 0) { 12 this.balance += amount; 13 console.log(`${amount} deposited. New balance: ${this.balance}`); 14 } else { 15 console.log("Deposit amount must be positive."); 16 } 17 } 18 19 // Method to withdraw money 20 withdraw(amount) { 21 if (0 < amount && amount <= this.balance) { 22 this.balance -= amount; 23 console.log(`${amount} withdrawn. Remaining balance: ${this.balance}`); 24 } else { 25 console.log("Insufficient balance for the withdrawal or amount is not positive."); 26 } 27 } 28} 29 30// Create an instance of BankAccount 31const account = new BankAccount("Alex", 1000); // An account with initial balance of 1000 32 33// Perform some transactions 34account.deposit(500); // Deposit money 35// Output: 500 deposited. New balance: 1500 36 37account.withdraw(200); // Withdraw money 38// Output: 200 withdrawn. Remaining balance: 1300 39 40console.log(`Final balance in ${account.holderName}'s account: ${account.balance}`); 41// Output: Final balance in Alex's account: 1300
This example further illustrates how classes effectively encapsulate data (properties) and functionalities (methods), enabling us to mimic real-life scenarios. Here, the BankAccount
class allows the creation of objects representing bank accounts, emphasizing the powerful organizational benefits of using classes in JavaScript.
Great work revisiting JavaScript classes, their properties, and methods. JavaScript classes help organize your code, improving its readability and manageability. Now, test your understanding with exercise problems to solidify your newly refreshed knowledge. Happy coding!