Day 6 of #100DaysOfCode!
Christian Falucho
Posted on June 22, 2021
Today's progress๐
I worked on inheritance, DRY (Don't Repeat Yourself) and supertype (parent). The benefit of inheritances and DRY is so that you don't rewrite code and it is about writing less code on your application. This way you deal with less problems (bugs) and write cleaner code. You can just imagine code can get extremely complex as it continues to grows. So it's better to find ways to minify it.
What I learned
I learned more about objects, prototypes and inheritances. The examples I worked on will hopefully explain how inheritance works and the benefits of it.
So what is inheritance
in Object-oriented programming? Inheritance allows for one class to inherit (or obtain) the attributes and methods of another class. The class whose properties and methods are inherited is known as the Parent
class.
The example below shows two object constructors and they both have a something in common, which is the drive
method.
function Car(){}
Car.prototype = {
constructor: Car,
drive: () => {
console.log("Vroom vroom")
}
}
function Motorcycle() {}
Motorcycle.prototype = {
constructor: Motorcycle,
drive: () => {
console.log("Vroom vroom")
}
}
Because we know both vehicles can both be driven and make the sound Vroom vroom, we can simplify and reduce the code by using the DRY principle and create a supertype (or parent) called Vehicle
and removing the drive method from both Car and Motorcycle and putting it in Vehicle.
So let's go ahead and create that.
//child object
function Car(){}
Car.prototype = {
constructor: Car,
drive: () => {
console.log("Vroom vroom")
}
}
//child object
function Motorcycle() {}
Motorcycle.prototype = {
constructor: Motorcycle,
drive: () => {
console.log("Vroom vroom")
}
}
// parent object
function Vehicle(){
}
Vehicle.prototype = {
constructor: Vehicle,
drive: () => {
console.log("Vroom vroom")
}
}
Inheritance
We created a supertype, used the DRY principle and now we want to apply inheritance. In other words, we want to inherit from the supertype, in this case the Vehicle
object. We can create a new instance of Animal simply by using a the method
Object.create(obj)
. This will create a new object and set obj
as the new object's prototype.
Here is what that looks like.
Car.prototype = Object.create(Vehicle.prototype)
let honda = new Car();
console.log(honda.drive());
//output: "Vroom vroom"
The subtype (or child) Car
is now an instance of Vehicle. When we create a new Car
object and store it into variable honda. honda
now inherits all of Vehicle
's properties and thus can perform the drive()
method.
Posted on June 22, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.