Object-Oriented Programming In javascript

Object-Oriented Programming In javascript

OOP in javascript using ES6 class syntax

ยท

6 min read

What is the Object?

In javascript Object is a data type that is used for storing a collection of data and methods. Like in the below example we are storing different data and methods related to the user collectively in the object.

const user = {
  firstName: "Omkar",
  lastName: "Kolate",
  userName: "omkarkolate",
  emailId: "omkarkolate@email.com",
  introduction() {
   console.log(`Hi I am ${this.firstName} ${this.lastName}`);
  }
}
user.introduction(); // Hi I am Omkar Kolate

this referred to the current object context. in this case, it's a user.

What is object-oriented programming?

As we saw in the above example that we are representing a user which is a real-world entity by using an object in the program.

Representing real-world entities in the program using objects and writing a program oriented on that objects is called object-oriented programming.

What is a prototype?

Javascript is a prototype-based language.

We have created one object but what if we want to create multiple objects similar to that. We can do it by using a prototype of an object, now what is a prototype?

Prototype is like a template object describing how the object will look like.

Now, the question is how to create this prototype, and the answer is by declaring class.

What is class ?

Using the class declaration we can create a template for creating objects. As they say, it is a prototype for the object.

Variables that we create in the template are properties of the class and functions are methods of the class.

Ok, but how to create this template and how the object will create from it, here comes constructor function to help you.

What is constructor?

Constructor is a special function inside class that initializes the object by assigning values to the properties.

new keyword helps to create a new instance of the object and then the constructor function initializes that instance of the object. This process is called instantiation.

// Creating prototype or template
class User {
  constructor(firstName, lastName, userName, emailId) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.userName = userName;
    this.emailId = emailId;
  };
  introduction() {
    console.log(`Hi I am ${this.firstName} ${this.lastName}`);
  };
};
// Creates new instance of object and initialize it
const user1 = new User("Omkar", "Kolate", "omkarkolate", "omkarkolate@email.com");

console.log(user1);
/*
 { 
    firstName: 'Omkar', 
    lastName: 'Kolate', 
    userName: 'omkarkolate', 
    emailId: 'omkarkolate@email.com' 
 }
*/

user1.introduction(); // Hi I am Omkar Kolate

While writing class names there is a naming convention to it that its first letter should be in upper case.

Object Oriented Concepts

  1. Encapsulation
  2. Abstraction
  3. Inheritance
  4. Polymorphism

They are also referred to as pillars of object-oriented programming(OOP).

1. Encapsulation

Binding or encapsulating properties and methods inside the object called Encapsulation

As we see in the above example we bounded or encapsulated the properties and methods inside an object.

2. Abstraction

In the above example, we have the introduction method which is giving the introduction of the user. So basically when we want the user's introduction we can simply call the method and get it.

By doing this, we have abstracted out the process of getting user data and creating an introduction out of it.

Abstraction is creating a simple model of a more complex thing, by abstracting out the process to do it.

3. Inheritance

Now we have the User class but, suppose some users bought a prime subscription they have some extra features in their profile. But basic properties like first name, last name will be going to remain the same in both cases.

So, instead of declaring a new class for prime users, we can take or inherit properties and methods from the User class, and also can add new properties and methods to the prime user class.

Here the User class is acting like a parent class and the prime user class is child class.

Inheriting properties and methods from parent class to child class is called Inheritance.

For example, suppose the prime user has the feature of setting emoji in their profile, so we need to add this property with inherited properties from the User class.

class PrimeUser extends User {
    constructor(firstName, lastName, userName, emailId, emoji) {
        super(firstName, lastName, userName, emailId);
        this.emoji = emoji;
    }
}

const primeUser1 = new PrimeUser("Elon", "Musk", "elonmusk", "elonmusk@tesla.com", "๐Ÿ˜Ž");

console.log(primeUser1);

/*
{
  firstName: 'Elon',
  lastName: 'Musk',
  userName: 'elonmusk',
  emailId: 'elonmusk@tesla.com',
  emoji: '๐Ÿ˜Ž' 
}
*/

primeUser1.introduction(); // Hi I am Elon Musk

There are two new keywords you may have seen first is extends and the second is super.

By writing extends we are saying that we are extending the User class by inheriting properties and methods into the PrimeUser class.

As we are inheriting from the User class, we need to instantiate it, so by writing super we are calling the constructor of parent class here it is User class and instantiating it.

Then we are adding new property emoji to the PrimeUser.

If you observed at the end of the code we are calling the introduction method and we are getting output as per the User class introduction method.

But, what if we want a new introduction for our prime users with emoji, we can do it by using polymorphism.

4. Polymorphism

Method with the same name but different implementation in different inherited classes called as Polymorphism

class PrimeUser extends User {
    constructor(firstName, lastName, userName, emailId, emoji) {
        super(firstName, lastName, userName, emailId);
        this.emoji = emoji;
    }

    introduction() {
      console.log(`Hi I am ${this.emoji} ${this.firstName} ${this.lastName}`);
    }
}

const primeUser1 = new PrimeUser("Elon", "Musk", "elonmusk", "elonmusk@tesla.com", "๐Ÿ˜Ž");

console.log(primeUser1);

/*
{
  firstName: 'Elon',
  lastName: 'Musk',
  userName: 'elonmusk',
  emailId: 'elonmusk@tesla.com',
  emoji: '๐Ÿ˜Ž' 
}
*/

primeUser1.introduction(); // Hi I am ๐Ÿ˜Ž Elon Musk

Now, we got a new introduction for our prime user with emoji, we achieved it by the polymorphism, same name but different implementation.


TL;DR

  1. Object is a data type in javascript to store the collection of data.
  2. Representing real-world entities in the program using objects and writing a program oriented on that objects is called object-oriented programming.
  3. Javascript is a prototype-based language.
  4. Prototype is like a template object describing how the object will look like.
  5. Using the class declaration we can create a template for creating objects.
  6. new keyword helps to create a new instance of the object and then the constructor function initializes that instance of the object. This process is called instantiation.
  7. Binding or encapsulating properties and methods inside the object called Encapsulation
  8. Abstraction is creating a simple model of a more complex thing, by abstracting out the process to do it.
  9. Inheriting properties and methods from parent class to child class is called Inheritance.
  10. Method with the same name but different implementation in different inherited classes called as Polymorphism

ย