Object Oriented Concepts and its mapping in Javascript

In the field of IT, one of the most commonly used terms is “Object Oriented” Programming(OOP). It takes a while to fully understand and grasp the concepts of OOP, but once you do, the gates of the programming world are wide open for you !

Let’s start with first understanding the concepts of OOP with a real world example and then dig deeper to understand how each of these concepts are achieved in JavaScript programming.

There are two ways to approach any problem.

  1. To list down step by step what needs to be done to solve the problem. This is the procedural approach.
  2. The other way is to break down the problem into smaller objects related to the big problem. Each object definition contains its properties and the actions (methods) which can be performed on the object. All these objects make up several reusable units to solve the bigger problem. Now the problem is solved by the interaction between all these objects defined.

This second approach is the Object Oriented approach, where everything revolves around Objects to make our life easier!

Combining Object Oriented principles with the power of JavaScript – the results will surely be Outstanding!

Let’s take a break here and I will tell you something about Buddy, my beloved pug.

  • Buddy(Object) is a Dog(Class).
  • Buddy is 2 years old and weighs 15 pounds(Properties).
  • Buddy belongs to Pug breed(Property) of companion dogs.
  • He barks, sits , goes for a walk like any other Dog(methods)
  • I keep record of Buddy’s sleep patterns(method) by using his sleep data- Encapsulation
  • I take Buddy for regular health check ups(method) where different parameters(height,weight, skin, teeth etc.) are checked where I am not concerned with the details of how the parameters are measured but finally to know that my Buddy is healthy) – Encapsulation and Information hiding
  • Buddy has a friend in the neighbourhood named Ace, another dog(same basic characteristics of the Dog class) – Inheritance
  • There is difference in the behaviour of Buddy and Ace,though they are both dogs. They have their unique mannerisms in the way they sit, run, bark. The same activity exhibited in their own style – Polymorphism

Now you know why I started talking about Buddy, while introducing you to the OOP concepts.

Object

The first and most elemental concept is an Object. Object as per OOP, is a specific instance of a Class, which is a more generic term.

So Dog is a class and Buddy is an object, an instance of the Dog class.

JavaScript(JS) does not have classes but the behaviour of Classes is simulated using JS Functions and objects.

Note:

JavaScript classes introduced in ECMAScript 2015 provide a syntactical way of dealing with JS objects to provide for the Object Oriented features of the language.

In JS, an object is defined as an unordered list of properties consisting of a name (always a string) and a value. When the value of a property is a function, it is called a method.

This provides an implementation to any real-life object with properties and methods related to it.

Object definition using Object Literals

The simplest and convenient way to define objects is using object literals as shown below.

var pet= {
name : “Buddy”,
breed:  ”Pug”,
weight : 15,
Age: 2,
bark : function() {
console.log(“Woof! Woof!”);
},
weighthealthcheck : function(){
If (weight>12 && weight<16)
console.log(this.name +’is healthy’);
else
console.log(‘Needs attention’);
}
}

This is a convenient way to define an object for immediate use, giving all its properties and methods. So here the var pet(object) represents a specific dog named Buddy. This works well for less number of objects, but what now if we want to define all the other pets in my neighbourhood like Ace. I will have to list out all its properties and methods again,something like this.

var pet2 = {
name : “Ace”,
breed:  ”Labrador”,
weight : 60,
Age: 1,
bark : function() {
console.log(“Baw! Baw!”);
}
}

That’s a lot of redundant work!

Object constructors save the day to create many similar objects! Let’s see how!

Object Constructors

An Object constructor is a function which returns an object created as per the definition.

First we provide the definition of the constructor , and then use it to create objects.

The Object Constructor is synonymous to a Class in traditional OOP languages, which is used to create new instances/objects of the same class with the properties of the class.

Syntactically same as a function, this is differentiated by following the naming convention of using capitalized first letter of the name.

function Pet(name, breed, age){
this.name =name;
this.breed= breed;
this.age = age;
this.walk = function(){
if (this.breed ===”Pug”){
console.log(“Walks 5 km”);
else if(this.breed ===”Labrador”){
console.log(“Walks 10 km”);
}
else{
console.log(“How long can you walk at a stretch?”);
}
}

Now we can use the above definition to create as many of our pets. Same as instantiating the class by creating new objects.

var buddy = new Pet(“Buddy”,”Pug”,2);
var ace = new Pet(“Ace”,”Labrador”,1);

The new keyword creates a new empty object and the parameter this points to this newly created object. Next when the function is called, the values gets assigned to the new object as per the definition of the constructor function. The newly created object reference is returned and assigned to the variable which now represents the new object like buddy,ace.

Note:

If the number of parameters is huge, the object constructor also doesn’t look pretty! In such cases, the combination of the above two methods can be used; an Object Literal can be defined first with all the parameters and it can be passed as a single parameter to the Object Constructor.

We now understand the two ways in which objects can be defined and how they imitate classes in OOP.

The Object Constructor implements the class behaviour of traditional Object oriented programming. In our example, Pet behaves as the parent class from which new instances of objects are created. But as in traditional OOP, there is no privacy; all properties are public. There is no direct way to access the super methods i.e constructor of the parent. We will see how this can be achieved in JavaScript a little later.

First let’s understand some of the limitations of using the Object Constructor approach.

When a new object is created using an object constructor, the new reference which gets created holds all the object properties including methods.

So every time a new Pet is defined it has its own copy of bark method even though it’s the same method. This is definitely not the efficient way to handle objects as it leads to unnecessary memory allocated to all the extra copies of the same method.

Is it real reuse ?? On the face, it looks like, but actually isn’t!

Also if you ever forget to include the new prefix when calling a constructor function, then this will not be bound to a new object, instead bound to the global object resulting in unwanted surprises without any warnings.

JavaScript’s extra strong object model, Prototype is the more flexible and powerful way to handle objects and their reuse.

Prototypes and Inheritance

Prototypes strengthen the JavaScript objects and provide the power of prototypal inheritance, the true inheritance in JavaScript.

For our buddy example, we can define a Pet Prototype, which will have all the common properties and methods.

Let’s see how we setup this prototype:

function Pet(name, breed, age){
this.name =name;
this.breed= breed;
this.age = age;
}

We include the properties which are not common and each object will have its own copy of these properties. We do not include the methods or common properties here as they will be defined in the prototype as below.

Pet.prototype.bark= function(){
console.log(“Woof! Woof!”);
}
Pet.prototype.run = function(){
if (this.breed ===”Pug”){
console.log(“Walks 5 km”);
else if(this.breed ===”Labrador”){
console.log(“Walks 10 km”);
}
else{
console.log(“How long can you walk at a stretch?”);
}
}
Pet.prototype.type =”Friendly”;

Here we have listed all the common methods and properties for the prototype which will be inherited by all objects of the prototype.

Now we can create instances of the prototype(similar to how we use Object Constructor).

var buddy = new Pet(“Buddy”,”Pug”,2);

var ace = new Pet(“Ace”,”Labrador”,1);

Now if we invoke

buddy.run();

For any invocation, the method is looked up in its prototype if not available in the object directly.

We can override the prototypal methods and properties to have specific values for the specific object.

buddy.bark= function(){
console.log(“Baw! Baw!”);
}

We can build a chain of prototype inheritance where a prototype can further inherit from another prototype and so on. Read more about Inheritance to understand in depth.

Now we understand how JavaScript prototypes provides the power of inheritance and reuse.

Next we will see another important concept of Object Oriented programming, Encapsulation and Information Hiding.

Encapsulation through Closures

Encapsulation in Object oriented programming aims to achieve two capabilities:

  • A way to bundle data along with the methods operating on that data.
  • A mechanism for limiting direct access to some of the data by hiding it within the bundle, also known as information hiding.

As we saw earlier, JavaScript Objects provide the capability to bundle data and methods operating on the data together, but then we don’t have any concept of private methods, which can only be called by other methods in the same object.

Why do we need private methods?

  • Mainly to restrict access to code.
  • Secondly they provide a powerful way to declutter the global namespace by keeping the non-essential methods as private and only the essential ones in the public or global namespace.

So let’s see how we can bring in some privacy in JavaScript. This is done using Closures in JavaScript.

A closure is a function together with its referencing environment.

Lets check our buddy weight without making all the details public.

    
        var buddyWeight = (function () {
            var status = 'Healthy';
            var weight = 14;
            var minWeight = 14;
            var maxWeight = 18;
            function checkHealth(val) {
                weight += val;
                if (weight >= minWeight && weight 
                    status = 'Healthy!';
                }
                else {
                    status = 'UnHealthy!';
                }
            }
            return {
                improveWeight: function () {
                    checkHealth(1);
                },
                reduceWeight: function () {
                    checkHealth(-1);
                },
                value: function () {
                    return status;
                }
            };
        })();
        console.log(buddyWeight.value());
        buddyWeight.improveWeight();
        buddyWeight.improveWeight();
        console.log(buddyWeight.value());
        buddyWeight.reduceWeight();
        console.log(buddyWeight.value());

In this approach we are creating an encapsulated scope by immediately executing the function with the function expression followed by (); and returning only the essential parts what is needed to be exposed.

This method is also called namespacing as we are creating a local namespace and returning only required data to the global namespace.

In our example, we are modifying and checking weight of Buddy, without the details of the weight being exposed to the global namespace as we are only concerned with the status being Healthy or Not. This is the beauty of JavaScript Encapsulation!

CONCLUSION

Now you are empowered with the knowledge of Object Oriented Programming in JavaScript. Hope you can make full use of these great programming principles in the best way to your advantage and write powerful code; Never say OOPS, Do OOPS!

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