Today we are going to discuss about classes and Inheritance.
What is a class? Class is a blueprint of object. Class has properties/attributes and implementation of behavior/methods.
From classes we create objects. So, what are objects? Objects are instances of classes, which we use to store data and perform actions.
Now let’s see how Java Script implement classes.
Before ES6 version classes are define using ‘function’ key word but the difference between function and a class is class start with capital letter and function start with simple letter.
When creating objects from classes in Java Script we use ‘new’ keyword. If there a function and created an object using ‘new’ keyword. It is indication that function is a class.
Below example indicates how constructors are define before ES6 version.
In the ES6 version release java Script core team added a ‘class’ reserved keyword to the Java Script to make our life easier but ‘class’ keyword is not yet adopted to all the Java Script engines.
Just like in Java we can use ‘class’ keyword to define classes which is much easier to remember. Below example shows how to use ‘class’ key word to define classes.
Now let’s see how to define constructor for above example.
Before ES6 version release if we want to add behaviors to the class, we should create a prototype. So, to demonstrate this I am going to create a new Vehicle class.
In present (After ES6 version release) to add behaviors to the class we use methods.
Inheritance is one of the main concepts of Object Oriented Programming.it is the mechanism of one class derives from another class.
Now let’s see how Inheritance implemented in Java Script
Before ES6 version releases inheritance is defined using prototype. Above example 6(check example 6) we created Vehicle class and we want to create a sub class for Vehicle class call Van. To do that we have to create Van class and inherit Vehicle class properties and methods.
Now let’s see how to do that in the below example.
After ES6 version Java Script introduced ‘extends’ key word along with the ‘class’ key word, to implement inheritance relationship which is much easier than using above method. Maybe you wonder why I thought you something hard when there is an easy method. Because just like ‘class’ key word ‘extends’ key word is not supported by all the Java Script engines. So, it is better to know both the ways to prevent happening any kinds of errors.
In next chapter I will discuss about ‘this’ keyword and strict notation.