Greetings, future OOP experts! JavaScript’s dynamic nature allows us to explore a multitude of ways to structure and manage our data and functions. At the core of this lies prototypes and ES6 classes. If you’ve ever wondered how inheritance works in JavaScript or how to encapsulate data and methods into structured units, you’re at the right place.
Let’s embark on this insightful journey!
Understanding Classes and Prototypes
Prototypes: Every JavaScript object has a prototype, which is itself an object. This prototype object has its own prototype, forming a prototype chain, ending up at Object.prototype. It’s this chain that forms the basis of inheritance in JavaScript.
Example:
function Dog(name) {
this.name = name;
}
Dog.prototype.bark = function() {
console.log(`${this.name} says woof`);
};
const myDog = new Dog('Max');
myDog.bark(); // Outputs: Max says woof
ES6 Classes: While prototypes are powerful, ES6 classes provide a much cleaner syntax to define and inherit objects. Example:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const myDog = new Dog('Rex');
myDog.speak(); // Outputs: Rex barks.
Exercise
Let’s get those coding gears moving:
- Create a class named Vehicle with properties for make, model, and year.
- Define a method getDetails in this class that returns a string with all these details.
- Extend the Vehicle class with a new class called Car. Add an additional property isElectric.
- Override the getDetails method in the Car class to also mention if the car is electric.
Hints for the exercise:
- Use the super keyword inside the Car class to call the parent class’s constructor and methods.
- Utilize the extends keyword to achieve inheritance.
Sample code to start with:
class Vehicle {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
getDetails() {
return `${this.year} ${this.make} ${this.model}`;
}
}
class Car extends Vehicle {
constructor(make, model, year, isElectric) {
super(make, model, year);
this.isElectric = isElectric;
}
getDetails() {
let baseDetails = super.getDetails();
return `${baseDetails} - Electric: ${this.isElectric}`;
}
}
const myCar = new Car('Tesla', 'Model S', 2022, true);
console.log(myCar.getDetails()); // Outputs: 2022 Tesla Model S - Electric: true
Conclusion
Kudos! You’ve now been introduced to the world of prototypes and ES6 classes in JavaScript. This understanding lays a foundation for the Object-Oriented Programming paradigm in JS. As you proceed, you’ll find these concepts play a central role in building scalable, maintainable, and structured applications.
Keep coding, and enjoy the journey of continuous learning!