Introduction to Object-oriented Programming in JavaScript
As JavaScript is wide utilized in net Development,
during this article, we’d explore a number of the thing-oriented mechanism supported by JavaScript to induce most out of it.
a number of the common interview question in JavaScript on OOPS includes,-
“How Object-Oriented Programming is enforced in JavaScript? however they take issue from different languages? are you able to implement Inheritance in JavaScript then on…”
There are sure options or mechanisms that make a Language Object Oriented like:
- Object
- Classes
- Encapsulation
- Inheritance
Let’s dive into the small print of every one amongst them and see however they’re enforced in JavaScript.
Object– an Object may be a distinctive entity that contains property and strategies. for instance “car” may be a real-world Object, that have some characteristics like colour,
type, model, H.P. and performs sure action like drive. The characteristics of an Object are referred to as Property, in Object-oriented Programming and therefore the actions are referred to as strategies.
an object is an instance of a category. Objects are all over in JavaScript virtually every component is an Object whether
or not it’s a perform, arrays and string.
Note: a technique in javascript may be a property of an object whose worth is a perform.
The object is created in 2 ways in which in JavaScript:
- Using an Object Literal:
//Defining object
let person = {
first_name:'Kishan',
last_name: 'Kaushik',
//method
getFunction : function(){
return (`The name of the person is
${person.first_name} ${person.last_name}`)
},
//object within object
phone_number : {
mobile:'9893',
landline:'7869'
}
}
console.log(person.getFunction());
console.log(person.phone_number.landline);
Output:
- Using an Object Constructor:
//using a constructor
function person(first_name,last_name){
this.first_name = first_name;
this.last_name = last_name;
}
//creating new instances of person object
let person1 = new person('Kishan','Kaushik');
let person2 = new person('Durgesh','Kaushik');
console.log(person1.first_name);
console.log(`${person2.first_name} ${person2.last_name}`);
Output:
Using Object.create() method: the item.create() technique creates a replacement object, mistreatment an existing object because of the epitome of the fresh created object.
// Object.create() example a
// simple object with some properties
const coder = {
isStudying : false,
printIntroduction : function(){
console.log(`My name is ${this.name}. Am I
studying?: ${this.isStudying}.`)
}
}
// Object.create() method
const me = Object.create(coder);
// "name" is a property set on "me", but not on "coder"
me.name = 'Kishan';
// Inherited properties can be overwritten
me.isStudying = 'True';
me.printIntroduction();
Output:
Classes– Classes are the blueprint of an Object. a category will have several Object, as a result of class could be a templet whereas Object is instances of the category or the concrete implementation.
Before we tend to move additional into implementation, we must always recognize in contrast to different Object bound Language there’s no categories
in JavaScript we’ve solely Object. To be a lot of precise, JavaScript could be an epitome primarily based object bound language,
which suggests it doesn’t have classes rather it outline behaviours mistreatment builder operate and so utilise it using the epitome.
Note: Even the classes provided by ECMA2015 are objects.
Example:
Let’s use ES6 categories then we are going to investigate the ancient manner of process Object and simulate them as classes.
// Defining class using es6
class Vehicle {
constructor(name, maker, engine) {
this.name = name;
this.maker = maker;
this.engine = engine;
}
getDetails(){
return (`The name of the bike is ${this.name}.`)
}
}
// Making object with the help of the constructor
let bike1 = new Vehicle('Hayabusa', 'Suzuki', '1340cc');
let bike2 = new Vehicle('Ninja', 'Kawasaki', '998cc');
console.log(bike1.name); // Hayabusa
console.log(bike2.maker); // Kawasaki
console.log(bike1.getDetails());
Output:
Traditional manner:
// Defining class in a Traditional Way.
function Vehicle(name,maker,engine){
this.name = name,
this.maker = maker,
this.engine = engine
};
Vehicle.prototype.getDetails = function(){
console.log('The name of the bike is '+ this.name);
}
let bike1 = new Vehicle('Hayabusa','Suzuki','1340cc');
let bike2 = new Vehicle('Ninja','Kawasaki','998cc');
console.log(bike1.name);
console.log(bike2.maker);
console.log(bike1.getDetails());
Output:
As seen within the higher than example it’s abundant less complicated to outline and utilise object in ES6. Hence, we might be mistreatment ES6 altogether our examples.
Encapsulation – the method of wrapping property and performance inside one unit is thought as encapsulation.
Let’s perceive encapsulation with an example.
//encapsulation example
class person{
constructor(name,id){
this.name = name;
this.id = id;
}
add_Address(add){
this.add = add;
}
getDetails(){
console.log(`Name is ${this.name},Address is: ${this.add}`);
}
}
let person1 = new person('Kishan',19);
person1.add_Address('Mumbai');
person1.getDetails();
Output:
In the higher than example we tend to merely produce a person Object mistreatment the builder and Initialize its property and use its functions we don’t seem to be trouble regarding the implementation details.
we tend to are operating with an Objects interface while not considering the implementation details.
Sometimes encapsulation refers to the concealment of information or data Abstraction which suggests representing essential options hiding the background detail.
Most of the OOP languages offer access modifiers to limit the scope of a variable, however, there aren’t any such access modifiers in JavaScript
but there is sure manner by that we will prohibit the scope of a variable inside the Class/Object.
Example:
// Abstraction example
function person(fname,lname){
let firstname = fname;
let lastname = lname;
let getDetails_noaccess = function(){
return (`First name is: ${firstname} Last
name is: ${lastname}`);
}
this.getDetails_access = function(){
return (`First name is: ${firstname}, Last
name is: ${lastname}`);
}
}
let person1 = new person('Kishan','Kaaushik');
console.log(person1.firstname);
console.log(person1.getDetails_noaccess);
console.log(person1.getDetails_access());
Output:
In the higher than example we tend to try and access some property(person1.firstname) and functions(person1.getDetails_noaccess) however
it returns undefine whereas there could be a technique that we will access from the person object(person1.getDetails_access()), by dynamic, the thanks to outlining a operate we will prohibit its scope.
Inheritance – it’s a plan during which some property and strategies of an Object are being employed by another Object. in contrast to most of the OOP languages wherever categories inherit classes, JavaScript Object inherits Object
i.e. sure options (property and methods)of one object will be reused by different Objects.
Let’s perceive inheritance with an example:
//Inhertiance example
class person{
constructor(name){
this.name = name;
}
//method to return the string
toString(){
return (`Name of person: ${this.name}`);
}
}
class student extends person{
constructor(name,id){
//super keyword to for calling above class constructor
super(name);
this.id = id;
}
toString(){
return (`${super.toString()},Student ID: ${this.id}`);
}
}
let student1 = new student('Mukul',22);
console.log(student1.toString());
Output:
In the higher than example we tend to outline a Person Object with sure property and technique and so we inherit the Person Object within the Student Object and use all
the property and method of person Object similarly define certain property and strategies for Student.
Note: The Person and Student object each has the same technique i.e toString(),
this is often referred to as Method Overriding. technique paramount permits method in a very kid category to possess an equivalent name and method signature as that of a parent class.
In the higher than code, a super keyword is employed to refer immediate parent category instance variable.
Please write comments if you discover something incorrectly, or you wish to share a lot of data regarding the subject mentioned higher than.