Object Oriented Programming in JavaScript

In this article I would like to post about the better way to program in JavaScript. First, I would try to list down few concepts about Object Oriented Programming and then  I would try and explain how these concepts can be incorporated in JavaScript. This topic is big in itself so I would break this topic into various articles. Following are the articles related to this topic.

  1. OOP Part 1 – Basics of OOP, how to implement OOPs concepts in JS
  2. OOP Part 2 – Advance concepts of OOPs, how to implement OOPs concepts in JS
  3. OOP Part 3 – Working example of OOP in real world JS.

Object Oriented Programming (OOP)

So what exactly is OOP? Object Oriented Programming is way in which we deal with only objects and their behaviors. Objects are real world entities like Person, Car etc which have their own existence in real world. And as we know all the entities has some behavior or function which that entity can perform like a Person can talk, walk, swim etc similarly a Car can be Started, Driven etc.

So we have the following elements in OOP

  1. Class
  2. Object
  3. Method

Class is a specification or a generic structure which defines an entity for example Car is a generic structure which is sufficient in itself and it has its sole purpose.

Likewise, there can be a lot of Cars which can be of shapes, brands etc. So, each Car with a specific shape or a Brand and other features or specifications which differentiates it with other Cars is an entity or an Object. Each object has its own data which is also known as its state.

As discussed each entity has a behavior or function to perform which it performs by itself or is initiated by external entities. This function or behavior is known as a Method.

So why should we go for OOP instead of structural programming? OOP helps in structuring the code better which is more close to the nature. It helps in making the code much more readable and maintainable.

Main goals of OOP are as follows:

  1. Make the code maintainable
  2. Easily understandable
  3. Easily extensible

OOP in JavaScript

So, now lets see how these concepts are implemented in JavaScript. In this article we would see how a class can be created, how the data members are added to the class along with the methods or behaviors.

So, lets see first how the class is created. There is no class keyword in JavaScript to define a class.

//constructor of class Car
//Constructor is basically used to create any object from a class. 
//Its a method which is executed first whenever an object is created.
function Car(ModelName, Brand, TopSpeed){ 
 //private data members
 var modelName = ModelName;
 var brand = Brand;
 var topSpeed = TopSpeed;

 //public data member
 this.speed = 0;

 //behaviors
 this.getTopSpeed = function(){
                        return topSpeed;
                    };

 this.getModelName = function(){
                        return modelName;
                     };

 this.getBrand = function(){
                        return brand;
                 };

 this.getSpeed = function(){
                        return this.speed;
                 };

 this.setSpeed = function(speed){
                        this.speed = speed;
                 };

 this.displayInfo = function(){
                        document.write("<br/>Top Speed : " + this.getTopSpeed() + " mph");
                        document.write("<br/>Model Name : " + this.getModelName());
                        document.write("<br/>Brand : " + this.getBrand());
                        document.write("<br/>Current Speed : " + this.getSpeed() + " mph");
                        document.write("<br/><br/><br/>");
                 };
 }

As we can see in the above example, we have created a class named “Car” which has data members “modelNumber”, “brand”, “topSpeed”, and “speed”.

Also, we have defined behaviors namely “getTopSpeed”, “getModelName”, “getBrand”, “getSpeed”, “setSpeed”, “displayInfo”.

Now, lets see how we can create the instance of this class “Car” and use or call its methods.

 var myCar = new Car("E220","Mercedes", 100);
 myCar.displayInfo();
 document.write("Setting the speed to 25mph<br/><br/>");
 myCar.setSpeed(25);
 myCar.displayInfo();

The above example would display the following output.

Top Speed : 100 mph
Model Name : E220
Brand : Mercedes
Current Speed : 0 mph

Setting the speed to 25mph

Top Speed : 100 mph
Model Name : E220
Brand : Mercedes
Current Speed : 25 mph

As we can see in the above example, we can create any object by using a new keyword before the class name and passing the parameters as desired by the constructor.

 var myCar = new Car("E220","Mercedes", 100);

Also, we can call the method by using the object name followed by dot(“.”) and the method name along with the parameters desired by the method if any.

myCar.displayInfo();

As you can see that there are some data members which have this keyword before them  and some have no this keyword but have var keyword before them. Let me explain the reason behind it.

If we use this keyword before the data member, then the data member would be public i.e. it can be accessed by instance or object.  For example, we can set or get the speed by directly accessing it from object like the following:

 myCar.speed = 30;//works fine

But we can’t set or get the topSpeed by directly accessing it from object like the following:

 myCar.topSpeed = 30;//error

So, in the above example we saw how we can create basic classes and define public and private data members. Also, we saw how we can create a method associated with the class. In my next article I would discuss about advance concepts in OOP and how we can implement those concepts in JavaScript.

Hope you like this article. Please feel free to comment and ask questions if you have anything or you like me to post about any specific stuff regarding JavaScript.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s