Week 3
3.9.1 Object-Oriented Programming (OOP) in JavaScript
Week 3
3.9.1 Object-Oriented Programming (OOP) in JavaScript
Object-Oriented Programming (OOP) is a programming paradigm that allows us to structure and organize our code using objects. JavaScript supports OOP principles through prototypes, classes, and constructors.
In JavaScript, every object inherits properties and methods from a prototype. Think of a prototype as a blueprint from which objects get their default behavior.
Example:
const person = {
greet: function() {
console.log("Hello!");
}
};
In this example, person can access inherited methods from its prototype, like toString() and hasOwnProperty().
JavaScript doesn’t use classical inheritance like Java or C++. Instead, it uses prototype-based inheritance.
function Animal(name) {
this.name = name;
}
// Adding a method to the prototype
Animal.prototype.speak = function () {
console.log(`${this.name} makes a noise.`);
};
const dog = new Animal("Buddy");
dog.speak(); // Buddy makes a noise.
Here, speak() is not directly inside dog, but it inherits it from Animal.prototype.
Instead of using constructors, we can also create prototypes manually:
const animal = {
speak: function () {
console.log(`${this.name} makes a sound.`);
}
};
const dog = Object.create(animal); // dog inherits from animal
dog.name = "Buddy";
dog.speak(); // Buddy makes a sound.
Object.create() creates an object with a specified prototype.
Before ES6, JavaScript used constructor functions for object creation. Now, we use the class keyword for a cleaner syntax.
function Car(brand, model) {
this.brand = brand;
this.model = model;
}
Car.prototype.getInfo = function () {
return `${this.brand} ${this.model}`;
};
const myCar = new Car("Toyota", "Corolla");
console.log(myCar.getInfo()); // Toyota Corolla
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
getInfo() {
return `${this.brand} ${this.model}`;
}
}
const myCar = new Car("Toyota", "Corolla");
console.log(myCar.getInfo()); // Toyota Corolla
Cleaner and more structured syntax
Easier to read and understand
Using the extends keyword, a child class can inherit from a parent class.
class ElectricCar extends Car {
constructor(brand, model, batteryLife) {
super(brand, model); // Calls the parent class constructor
this.batteryLife = batteryLife;
}
getBatteryLife() {
return `Battery lasts ${this.batteryLife} hours.`;
}
}
const myTesla = new ElectricCar("Tesla", "Model 3", 10);
console.log(myTesla.getInfo()); // Tesla Model 3
console.log(myTesla.getBatteryLife()); // Battery lasts 10 hours.
super() calls the parent class constructor to inherit properties.
The this keyword refers to the object that is calling the function. Its value depends on how the function is called.
console.log(this); // In a browser, this refers to the global window object
const user = {
name: "Alice",
greet() {
console.log(`Hello, ${this.name}!`);
}
};
user.greet(); // Hello, Alice!
Here, this refers to the user object.
function Person(name) {
this.name = name;
this.sayName = function () {
console.log(`My name is ${this.name}`);
};
}
const person1 = new Person("John");
person1.sayName(); // My name is John
In a constructor function, this refers to the new object being created.
const button = document.querySelector("button");
button.addEventListener("click", function () {
console.log(this); // Refers to the button element
});
When used inside an event listener, this refers to the DOM element that triggered the event.
Arrow functions behave differently with this.
const person = {
name: "Bob",
greet: () => {
console.log(`Hello, ${this.name}!`);
}
};
person.greet(); // Hello, undefined!
Why? Arrow functions do not have their own this, they inherit this from their parent scope.
Solution: Use a regular function
const person = {
name: "Bob",
greet() {
console.log(`Hello, ${this.name}!`);
}
};
person.greet(); // Hello, Bob!
Your task is to create an object-oriented model for animals using JavaScript.
1️⃣ Create an Animal class with:
A constructor(name, sound) that assigns a name and sound to the animal.
A makeSound() method that logs:
"{name} says {sound}!"
2️⃣ Create a Dog class that inherits from Animal and adds a fetch() method that logs:
"{name} is fetching the ball!"
3️⃣ Create a Cat class that inherits from Animal and adds a scratch() method that logs:
"{name} is scratching the furniture!"
4️⃣ Create objects for a dog and a cat using their respective classes and call their methods.
Bonus: Create an array of animals and use .forEach() to make each animal make its sound!
Master OOP in JavaScript, and you'll write cleaner, reusable, and more powerful code!
Next Up: Project.