JavaScript Classes – Object Oriented and Inheritance in Simple Steps for Beginners

ADMEC Multimedia Institute > Web Design > JavaScript Classes – Object Oriented and Inheritance in Simple Steps for Beginners

JavaScript is an object-oriented programming language, to explain OOP in simple language, Objects in JavaScript is same as objects in real world things like car, or a person like teacher. Objects oriented and inheritance is one of the complex topics which one understand while learning JavaScript course. We use object in programming language to represent them in simple way.

So, object is collection of data and function which are called as properties and methods when we code them inside the object.

As these objects for example, car have related properties like model, color, price, date of manufacture, it starts & stops, in same way we can create ‘car’ object in our program where we can store properties like model, color etc. or any function like start or stop. Storing data within object is also called as encapsulation.

In above example of car when we create simple introduction to a complex information like we want to only code care model, color and price as introduction it is called abstraction. A code which represent most important aspect of object for a programmer to work, it is abstraction.

Types of Making of Objects in JavaScript

Now, lets discuss how we can create objects in JavaScript. There are 2 main categories in which we can classify all objects:

1.  Standard or Built-in Objects

2.  Custom Objects

1. Standard built-in objects

We have already seen many of the JavaScript standard built-in objects in basic. For examples String, Array, RegExp, Date etc.

//In below Date object is created using the Date constructor and then we calll getFullYear() method to get the year.

var currentDate = new Date();
console.log(currentDate.getFullYear()); // output: 2018

2. Custom objects

There are two ways to create our own custom objects.

  1. By constructor function
  2. By declaring an object literal

1. Constructor function

Lets first see how we can create object by constructor function.

Example 1:

var obj = new Object();
    obj.name = "ravi";
    obj.run = function (abc){
     return this.name + " "+abc;
    }
alert(obj.run('runs very fast')); // ravi runs very fast

Example 2:

function Gallery(rows, cols){
    this.rows = rows;
    this.cols = cols;
}
var myGal = new Gallery(5,10);
alert( myGal.rows ); //5

Explanation : Here we have created a new Object Object() which has properties like ‘name’ and method ‘run’. Constructor give code an order where we can write properties and method separately and can create multiple object instances as and when required. This means code change to one instance, will not affect other instances.2. Literal objects:

var obj = {
'name' : "ravi",
"run" : function (abc){
    return this.name + " "+abc;
    },
  "key":{
   'number':"10",
    "code":"12"
   }
}
alert(obj.run('runs very fast')); //ravi runs very fast
alert(obj.key.number); //10

Explanation : Here we write properties and method of an object as we create an object and pass it to ‘obj’ variable.

Important: Both the examples give same output.

Prototyping in JavaScript

There is an extended feature of object-oriented programming called as Prototypes. With the help of Prototypes multiple objects can inherit features from one another and individual object can be extended by adding properties and methods to it.

Example 1:

function Gallery(rows, cols){
    this.rows = rows;
    this.cols = cols;
    this.totalCells = function (){
     return this.rows * this.cols;
    }
}
//extended our object
Gallery.prototype.initialImage = 0;
Gallery.prototype.nextImage = function(){
    return ++this.initialImage;
};
var myGal = new Gallery(5,10);
console.log(myGal.totalCells()); //50
console.log(myGal.initialImage); //0
console.log(myGal.nextImage()); //1

Explanation:  In above example we create a Gallery Object with two arguments and has properties like rows, cols & method totalCells. We create an instance of Gallery object and pass the parameter. Let’s say we can to extend the object and have another method which can be used separately. Here we can add prototype to the object and create new variable or methods. This reduce the code by eliminating creation of another object in the program.

Example 2:

Array.prototype.lowerCase = function(){
    for (var i = 0; i < this.length; i++) {
        this[i] = this[i].toLowerCase();
    }
};
var myArr = ['A','b','C'];
myArr.lowerCase();
alert(myArr);

Explanation: Adding prototype to an Array. It shows that built-in objects also can be prototype or we can say can be extended anytime.

Inheritance in JavaScript

It’s a feature where the parent object shares the feature with the child object. As in JavaScript there is no concept of classes the inheritance is done by prototypes, that is why it’s called prototypical inheritance

S.NOConstructor FunctionLiteral Object
1The properties and their values are separated by equal sign (=)They are separated by colon (;)
2At the end of each property you can have a semi-colon (;)Properties must be separated with a comma (,)
3To access ‘name’ value first we have to create an instance and then use the created instance and the property name separated by DOTTo access ‘name’ value you simply use obj.name.
function Gallery(){
    this.rows = 5;
    this.cols = 5;
    this.totalCells = function (){
     return this.rows * this.cols;
    }
}
//extended our object
Gallery.prototype.initialImage = 0;
Gallery.prototype.nextImage = function(){
   return ++this.initialImage;
};
function ImageGallery(){
    this.rows = 10;
}
//inheritance – inheriting attributes from Gallery object to ImageGallery object
ImageGallery.prototype = new Gallery;
var myImgGal = new ImageGallery();
alert(myImgGal.cols);
function VideoGallery(){
    this.cols = 10;
}
//inheritance – inheriting attributes from Gallery object to VideoGallery object
VideoGallery.prototype = new Gallery;
var myVidGal = new VideoGallery();
alert(myVidGal.rows);

Explanation:  In above example we are going to create 3 objects; Gallery a parent object while ImageGallery and VideoGallery as child objects where the common properties are shared from parent to child objects.

Firstly, we have created parent constructor object Gallery with common properties like rows, cols & method totalCells which will calculate total cell. Then we created two child constructor objects ImageGallery & VideoGallery. In ImageGallery with new row count & same cols as in Gallery Parent object. And VideoGallery with new cols and same rows as in the Gallery parent object. We can create both ImageGallery and VideoGallery new instances and pass them to variable myImgGal and myVidGal respectively.

And at last we accessed the properties of ImageGallery or VideoGallery using dot notation.

Objects inheritance is very useful to share a collection of data from one object to another without increasing the code unnecessarily. In case we have only one object, then it would be ideal to use object literal, and we definitely don’t need inheritance. This blog is all about the Object Oriented and Inheritance in JavaScript. To read more blogs go through our all JavaScript Blogs.

Related Posts

Leave a Reply

Call Now