BlogsDope image BlogsDope

Object-Oriented Programming in JavaScript

JavaScript is a prototype-based language, which means that objects have a prototype object that acts as a template object. The new object inherits properties and methods from the prototype object. This concept might be confusing now, but it will get clear in just a bit.

So, what is an object? It is an entity that has properties and methods attached to it. An object usually describes a real-life entity. Consider a person as an object. It has certain characteristics like height, age, gender, etc. It can also perform actions like walk, eat, dance, etc. Characteristics of an object are known as properties or attributes, and the actions are known as methods. In JavaScript, almost every element is an Object like arrays, functions, etc.

There are several ways to create an object. Let’s go through them one by one.

Object Literal


Objects are created using curly brackets in the form of keys and values. The value can be of any data type like string, number, function, array, another object, etc.

Let’s understand this using an example.

<script type="text/javascript">
Person = {
  name: "xyz",
  age: 20,
  height: "5ft",
  detail: function () {
    return (
      "Name: " + this.name + " Age: " + this.age + " Height: " + this.height
    );
  },
};

</script>

In the above example, we have created a Person object that has properties name, age, and height and a detail() method that returns the details of that object. The keyword this allows us to access the attributes of the current object.

The properties of the object can be accessed using the dot operator, i.e., Person.name. We can also retrieve it as Person["name"]. Let’s see an example.

Object in JavaScript

As you can see in the above example, we can also modify the value of the property using the assignment operator.

The disadvantage of this approach is that if you want to create another object, you would have to copy the same code and change the values, which is not a good way of coding as it is a repetition of code.

Object Constructor


Constructor functions are special functions that create objects, which have properties and methods attached to them. Let’s see an example.

<script type="text/javascript">
function Person(name, age, height) {
  this.name = name;
  this.age = age;
  this.height = height;
  this.details = function () {
    return (
      "Name: " + this.name + " Age: " + this.age + " Height: " + this.height
    );
  };
}
var p1 = new Person("xyz", 20, "5ft");
</script>

This example is the same as the previous example, but we have created an object instance using the constructor function. The Person() function contains the properties and methods of the object. We can create objects using the new keyword. The new keyword indicates JavaScript that it is a constructor function, not a regular function. Constructor functions are executed in a different way than regular functions. When a function is executed as a constructor function, JavaScript creates a new instance of the object and assigns it to this keyword. So, it is binding the context of the code that is in the function to this keyword, i.e., this keyword points to the current object.

Let’s display p1 object in the browser console. We get something like this.

Class in JavaScript

You can observe that it has an extra __proto__ property. It points to the object used as a prototype. Let’s extend it more.

__proto__ in JavaScript

So, what is happening? Refer to the first paragraph of this article. Remember when we said that a new object inherits its properties and methods from an object prototype. Here, the object instance p1 inherits from the prototype Person, which in turn inherits from the prototype Object. That’s why p1 has many other properties and methods than we defined in the constructor function, for example, toString(), valueOf(), etc. Check the figure below for more clarification.

Inheritance in JavaSciprt

We can access the property of an object using the dot operator, for example, p1.name, or using square brackets, i.e., p1[“name”]. Let’s look at an example.

Methods of class in JavaScript

Object.create()


We can also create object instances using the create() method of the Object. The syntax is Object.create(proto, propertiesObject). The proto argument represents the object to be used as the prototype for the newly created object. The optional propertiesObject lets you initialize object properties using an object literal having syntax similar to the second argument of the Object.defineProperties() method. Its default value is undefined. Object.create() returns an object instance with the given prototype object and properties. Consider the following example.

<script type="text/javascript">
Person = {
  name: "",
  age: 0,
  height: "",
  detail: function () {
    return (
      "Name: " + this.name + " Age: " + this.age + " Height: " + this.height
    );
  },
};

var p1 = Object.create(Person, {
  name: {
    value: "abc",
  },
  age: {
    value: 20,
  },
  height: {
    value: "5ft",
  },
  gender: {
    value: "female",
  },
});
</script>

creating object in JavaScript

In the above example, we have overwritten the values of the properties inherited from Person and set an additional new property gender on p1.

Class


Classes are blueprints or templates of an object. You can create many instances using a blueprint, i.e., you can create many objects using a class. Let’s see how we can create a class and its objects using ES6.

<script type="text/javascript">
class Person {
  constructor(name, age, height) {
    this.name = name;
    this.age = age;
    this.height = height;
  }
  detail() {
    return (
      "Name: " + this.name + " Age: " + this.age + " Height: " + this.height
    );
  }
}

var p1 = new Person("abc", 20, "5ft");
</script>

object in javascript

Class is created using a class keyword. Every class contains a constructor() method. Unlike other methods, it does not need the keyword function and a return statement. It gets implicitly called for the creation and initialization of an object. If you do not provide a constructor, a default constructor() method is called, i.e.,

constructor()
{
}

Note that JavaScript classes are functions (functions are objects), and therefore, they still use the same prototype-based inheritance.

That’s how we create classes using ES6. Let’s look at the traditional way.

<script type="text/javascript">
function Person(name, age, height) {
  (this.name = name),
    (this.age = age),
    (this.height = height),
    (this.details = function () {
      return (
        "Name: " + this.name + " Age: " + this.age + " Height: " + this.height
      );
    });
}
let p1 = new Person("xyz", 20, "5ft");
</script>

class method in JavaScript

Main Object-Oriented Programming Concepts


Inheritance

In the above section, we created a class Person to store some details about a person. Let us store data about students too. We want to include properties such as name, age, height, grade, and methods that return the grade of a student and personal details. Now, we can create a class Student that has all these properties and methods. It would work just fine. However, we can observe that there are some properties and methods that both classes have in common. Adding them separately in the Student class will result in the repetition of the code. As all students are persons, we can inherit the same features from the Person class. This mechanism is known as inheritance. The class that inherits features is known as the derived class or the child class, and the one being inherited from is called the base class or the parent class. JavaScript provides extends keyword for this purpose. Let's see.

Inheritance in JavaScipt

<script type="text/javascript">
class Person {
  constructor(name, age, height) {
    this.name = name;
    this.age = age;
    this.height = height;
  }
  detail() {
    return (
      "Name: " + this.name + " Age: " + this.age + " Height: " + this.height
    );
  }
}

class Student extends Person {
  constructor(name, age, height, grade) {
    super(name, age, height);
    this.grade = grade;
  }
  getGrade() {
    return "Grade of the student " + this.name + " is: " + this.grade;
  }
}

var s1 = new Student("abc", 12, "5ft", 7);
</script>

Student class in JavaScirpt

In the above example, the Student class extends the Person class, which means that the Student class is the child class, and the Person class is the base class. The super() method inside the Student’s constructor calls the constructor of the parent class.  If you do not call it, JavaScript throws an error. i.e.,

reference error in JavaScirpt

Note that you will get an error if you try to access this keyword before calling super() inside the constructor of a child class.

Encapsulation

Most of the time, we have some private data, and we want to restrict its direct access. Encapsulation means information or data hiding. It is a mechanism that restricts the direct access of data and binds data with the methods that operate on it. Consider the example below, in which the name of the person is private. By using the concept of encapsulation, we can only access it using setName() and getName() methods outside the scope of the class. We can say that the variable name is encapsulated inside the class Person.

<script type="text/javascript">
class Person {
  #name;
  constructor(name) {
    this.age = age;
  }

  getName() {
    return this.#name;
  }

  setName(name) {
    this.#name = name;
  }
}

var p1 = new Person("abc");

</script>

encapsulation in JavaScript

Abstraction

It means that showing only those aspects of the object that are relevant to the current scope. It hides unnecessary details from the user. For example, in our problem, we are not concerned with the phone number of the Person, so this property is irrelevant. Abstraction reduces scope and complexity.

Polymorphism

The word polymorphism means many forms. Polymorphism is an ability to create a property, a function, or an object that has more than one form. Consider the following example.

<script type="text/javascript">
class Person {
  constructor(name, age, height) {
    this.name = name;
    this.age = age;
    this.height = height;
  }
  detail() {
    return (
      "Name: " + this.name + " Age: " + this.age + " Height: " + this.height
    );
  }
}

class Student extends Person {
  constructor(name, age, height, grade) {
    super(name, age, height);
    this.grade = grade;
  }
  detail() {
    return (
      "Name: " +
      this.name +
      " Age: " +
      this.age +
      " Height: " +
      this.height +
      " Grade: " +
      this.grade
    );
  }
}

var s1 = new Student("abc", 12, "5ft", 7);
var p1 = new Person("abc", 12, "5ft");

</script>

In the above example, the Student class extends the Person class.  You can also observe that we have defined the detail() method again in the Student Class, which includes grades as well. This is known as Method Overriding. When we call s1.detail(), the Student’s method gets preference over the Person’s. i.e.,

method overriding in JavaScript

However, when we call p1.detail(), the detail() method of Person is invoked.

So, we have a Student class that extends the Person class and provides different implementation/form of the detail() method.


Liked the post?
A computer science student having interest in web development. Well versed in Object Oriented Concepts, and its implementation in various projects. Strong grasp of various data structures and algorithms. Excellent problem solving skills.
Editor's Picks
0 COMMENT

Please login to view or add comment(s).