Understand Object Oriented Programming
Learning Objectives
- Master JavaScript classes
- Understand prototypes and prototypal inheritance
- Apply OOP principles
- Create reusable class templates
- Solve problems using OOP
Section 10.1: Context: A Multiplayer RPG
RPG Game Scenario
Imagine building a multiplayer role-playing game with multiple character types:
- Warriors
- Mages
- Archers
Each has different properties and abilities. This is where OOP excels.
Section 10.2: JavaScript Classes
Creating a Class
class Character {
constructor(name, health, mana) {
this.name = name;
this.health = health;
this.mana = mana;
}
takeDamage(damage) {
this.health -= damage;
}
heal(amount) {
this.health += amount;
}
displayInfo() {
console.log(`${this.name} - HP: ${this.health}, Mana: ${this.mana}`);
}
}
// Create instances
let hero1 = new Character("Aragorn", 100, 50);
let hero2 = new Character("Gandalf", 80, 150);
hero1.takeDamage(10);
hero1.displayInfo(); // Aragorn - HP: 90, Mana: 50
The Constructor
Special method that runs when creating a new instance:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
let person = new Person("Alice", 30);
console.log(person.name); // Alice
Methods in Classes
class Calculator {
add(a, b) {
return a + b;
}
subtract(a, b) {
return a - b;
}
multiply(a, b) {
return a * b;
}
}
let calc = new Calculator();
console.log(calc.add(5, 3)); // 8
Class Inheritance
class Warrior extends Character {
constructor(name, health, mana, strength) {
super(name, health, mana);
this.strength = strength;
}
attack() {
return this.strength * 2;
}
}
let warrior = new Warrior("Conan", 150, 20, 25);
console.log(warrior.attack()); // 50
warrior.takeDamage(5); // Method from parent class
Section 10.3: Under the Hood: Objects and Prototypes
Prototypal Inheritance
Every object has a prototype chain:
let obj = {};
console.log(Object.getPrototypeOf(obj));
Prototype Methods
function Dog(name) {
this.name = name;
}
Dog.prototype.bark = function() {
console.log(this.name + " barks!");
};
let myDog = new Dog("Rex");
myDog.bark(); // Rex barks!
Classes vs Functions
Classes are syntactic sugar over prototypes:
// Using class
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + " makes a sound");
}
}
// Using constructor function (old way)
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + " makes a sound");
};
Section 10.4: Object-Oriented Principles
1. Encapsulation
Keep data private within objects:
class BankAccount {
constructor(owner, balance) {
this.owner = owner;
this._balance = balance; // Convention: _ means private
}
deposit(amount) {
this._balance += amount;
}
checkBalance() {
return this._balance;
}
}
let account = new BankAccount("Alice", 1000);
account.deposit(500);
console.log(account.checkBalance()); // 1500
2. Encapsulation with Getters/Setters
class CircleClass {
constructor(radius) {
this._radius = radius;
}
get radius() {
return this._radius;
}
set radius(value) {
if (value > 0) {
this._radius = value;
}
}
get area() {
return Math.PI * this._radius ** 2;
}
}
let circle = new CircleClass(5);
console.log(circle.area); // 78.54...
3. Polymorphism
Different classes with same method:
class Cat {
speak() {
console.log("Meow!");
}
}
class Dog {
speak() {
console.log("Woof!");
}
}
let cat = new Cat();
let dog = new Dog();
cat.speak(); // Meow!
dog.speak(); // Woof!
Coding Challenges
Challenge 10.1: Create a Dog Class
Task: Create a Dog class with:
- Constructor: name, breed, age
- Methods: bark(), getAge(), birthday()
Challenge 10.2: Create a Character Inventory Class
Task: Create an Inventory class:
- Store items in an array
- Methods: addItem(), removeItem(), listItems()
Challenge 10.3: Create an Account Class
Task: Create a bank Account class:
- Properties: accountHolder, balance
- Methods: deposit(), withdraw(), getBalance()
- Prevent negative balance
Key Takeaways
✅ Classes create reusable object templates
✅ Constructor initializes new instances
✅ Methods define behaviors
✅ Inheritance extends functionality
✅ Polymorphism allows different behaviors
✅ Encapsulation protects data
Quiz Questions
- What is the purpose of a constructor?
- How does inheritance work in JavaScript?
- What is polymorphism?
- What are getters and setters?
- How are classes different from objects?
Next Module: Module 11 - Discover Functional Programming