Understanding JavasScript OOPs
Unraveling the Essence of JavaScript Object-Oriented Programming
Introduction:
Many Developers doubt whether JavaScript is a Functional Programming language or Object Oriented!
In reality, It's Both!
JavaScript is a prototype-based procedural language, which means it supports both functional and object-oriented programming.
In this article, we will learn and use Object-Oriented Programming (OOP) concepts in JavaScript.
What is OOP?
OOP is a programming paradigm that believes in grouping data (properties) and methods (actions) together inside a box. It demonstrates the pattern of real-world objects.
There are two types of OOP languages:
1.Class-based languages.
2.Prototype-based languages.
So if you are coming from C++ or Java, you are familiar with Class-Based syntaxes.
But Javascript is a Prototype-Based Programming Language!
4 Main Pillars of OOPs:
There are four rules or main pillars of Object-oriented programming language. This defines how the data and actions associated with the data; are organized using code.
Abstraction
Encapsulation
Polymorphism
Inheritance
Does Javascript Have classes?
Yes and No!
What?
Confusing Right??
Let me explain this!
As I mentioned before, Javascript is a prototype-based Language; It doesn't have classes. We define the templates for objects using constructor functions or prototypes.
But Wait!
Javascript Does support the Class Keyword!
"The keyword class in JavaScript is actually a syntactic sugar over the prototype-based inheritance, which is already present and supported in JavaScript."
Though It allows us to use the class keyword, It uses its Prototype-based mechanism under the hood. This is to help the Developers coming from class-based languages like C++, and Java.
Object Literal:
It is a way to define an object using a simple and concise syntax. It allows us to create an object without using the traditional constructor syntax or the Object.create()
method.
Let's Understand with some examples,
Before Object Literals, We used to create objects using Object.create()
method Which was not much efficient.
const personPrototype = {
greet: function() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
};
const person = Object.create(personPrototype);
person.name = 'Arindam';
person.age = 18;
person.isStudent = true;
Here you can see the code is too long!
Whereas, With Object literals, you can easily write the same program as:
const person = {
name: 'Arindam',
age: 18,
isStudent: true,
greet() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
};
person.greet(); // Output: Hello, my name is Arindam and I'm 18 years old.
The 'this' Keyword:
Have you noticed that in the previous code, we have used this.name
instead of name
.
But why?
What's the significance of that "this" keyword?
Let's understand this with examples,
At first, we'll remove the this
keyword from the code and see what happens.
const person = {
name: 'Arindam',
age: 18,
isStudent: true,
greet() {
console.log(`${name}`);
}
};
person.greet(); // output:undefined
This program outputs undefined!
But why? We have already defined the name in the function!
This is because the greet function doesn't have any variable named name
. when we tried to access the name property, javascript searched in the function scope(which is the greet function scope) and returned undefined
.
To access the name
property of the person
object correctly within the greet
method, you need to use the this
keyword. The this
keyword refers to the current object (in this case, the person
object) that the method is being called on.
Here's the Bokish definition of 'this'
keyword:
The
this
keyword in JavaScript refers to the context in which a function is executed.
The 'new' Keyword:
"The
new
keyword in JavaScript is used to create instances of objects from constructor functions. It plays a crucial role in object-oriented programming as it facilitates the process of creating objects with specific properties and behaviours."
Didn't understand? No worries!
Let's understand this with some examples,
function User(username , age ){
this.username = username;
this.age = age;
return this.name
}
const User1 = User(Arindam , 18);
console.log(User1);//output: Arindam
Here we have created a function named User which returns its name property. And created User1.
And the output same as our prediction.
Now let's create another user and see what happens,
function User(username , age ){
this.username = username;
this.age = age;
return this.name
}
const User1 = User(Arindam , 18);
const User2 = User(Diya, 17);
console.log(User1); //Output: Diya
Here we have created another User (Here it's User2) and printed the previous User (Here it's User1).
But wait! The output is not the same as before!
User2 Has overwritten the value of User1. As you can understand this is a serious issue. To solve this issue we use the new
keyword.
Now, Let's do the same thing with new
keyword and see what happens:
function User(username , age ){
this.username = username;
this.age = age;
return this.name
}
const User1 = new User(Arindam , 18);
const User2 = new User(Diya, 17);
console.log(User1); //Output: Arindam
Here the new keyword created instances of the constructor function (in this case it's User). So, we get two copies/instances of the function and there's no chance of data being overwritten.
new
keyword with a regular function (not a constructor function) will not create a new instance and may lead to unexpected behaviour or errors. The new
keyword is specifically used with constructor functions to create and initialize instances of objects.Internal Working of new :
When you use the new
keyword with a constructor function, the following steps take place:
A new empty object is created. This new object will become the instance of the constructor function.
The
this
keyword inside the constructor function is set to point to the newly created object. This allows the constructor function to refer to and set properties on the newly created instance.The constructor function executes, and any properties or methods defined with
this
inside the constructor is added to the new instance.If the constructor function does not explicitly return an object, the new instance created by
new
is returned as the result of thenew
expression. This allows you to store the created instance in a variable and use it later.
Conclusion:
If you found this blog post helpful, please consider sharing it with others who might benefit. You can also follow me for more content on Javascript, React, and other web Development topics.
For Paid collaboration mail me at : arindammajumder2020@gmail.com
Connect with me on Twitter, LinkedIn, Youtube and GitHub.
Thank you for Reading :)