DEV Community

Cover image for OOPs in Javascript
NIKHIL GAUTAM
NIKHIL GAUTAM

Posted on • Edited on

OOPs in Javascript

There are certain features or mechanisms which makes a Language Object-Oriented like:

1.Object
2.Classes
3.Encapsulation
4.Inheritance

  1. Object– An Object is a unique entity that contains properties and methods. For example “car” is a real life Object, which has some characteristics like color, type, model, horsepower and performs certain actions like drive. The characteristics of an Object are called Properties in Object-Oriented Programming and the actions are called methods. An Object is an instance of a class. Objects are everywhere in JavaScript, almost every element is an Object whether it is a function, array, or string.

Note: A Method in javascript is a property of an object whose value is a function.

1. Using an Object Literal

//Defining object
let person = {
    first_name:'Ram',
    last_name: 'Prasad',

    //method
    getFunction : function(){
        return (`The name of the person is
        ${person.first_name} ${person.last_name}`)
    },
    //object within object
    phone_number : {
        mobile:'7399',
        landline:'6743'
    }
}
console.log(person.getFunction());
console.log(person.phone_number.landline);

Enter fullscreen mode Exit fullscreen mode

2. 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('Ram','Prasad');
let person2 = new person('Vishnu','Avasthi');

console.log(person1.first_name);
console.log(`${person2.first_name} ${person2.last_name}`);
Enter fullscreen mode Exit fullscreen mode

3. Using Object.create() method:

The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.

// Object.create() example a
// simple object with some properties
const student = {
    isWorking : false,
    printIntroduction : function(){
        console.log(`My name is ${this.name}. Am I
        Working?: ${this.isWorking}.`)
    }
}
// Object.create() method
const me = Object.create(coder);

// "name" is a property set on "me", but not on "student"
me.name = 'Ram';

// Inherited properties can be overwritten
me.isStudying = true;

me.printIntroduction();

Enter fullscreen mode Exit fullscreen mode

2. Classes
Classes are blueprint of an Object. A class can have many Objects because class is a template while Object are instances of the class or the concrete implementation.
Before we move further into implementation, we should know unlike other Object Oriented Language there are no classes in JavaScript we have only Object. To be more precise, JavaScript is a prototype based Object Oriented Language, which means it doesn’t have classes, rather it defines behaviors using a constructor function and then reuse it using the prototype.

JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript’s existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance.

// 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());

Enter fullscreen mode Exit fullscreen mode
// 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());

Enter fullscreen mode Exit fullscreen mode

3. Encapsulation – The process of wrapping properties and functions within a single unit is known as encapsulation.
Let’s understand 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('Ram',26);
person1.add_Address('Mathura');
person1.getDetails();

Enter fullscreen mode Exit fullscreen mode

In the above example we simply create a person Object using the constructor and Initialize its properties and use its functions. We are not bothered with the implementation details. We are working with an Object’s interface without considering the implementation details.
Sometimes encapsulation refers to the hiding of data or data Abstraction which means representing essential features hiding the background detail. Most of the OOP languages provide access modifiers to restrict the scope of a variable, but their are no such access modifiers in JavaScript but there are certain ways by which we can restrict the scope of variables within the Class/Object.

// 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('Ram','Prasad');
console.log(person1.firstname);
console.log(person1.getDetails_noaccess);
console.log(person1.getDetails_access());

Enter fullscreen mode Exit fullscreen mode

In the above example we try to access some property(person1.firstname) and functions(person1.getDetails_noaccess) but it returns undefined while their is a method which we can access from the person object(person1.getDetails_access()). By changing the way we define a function we can restrict its scope.

4. Inheritance – It is a concept in which some properties and methods of an Object are being used by another Object. Unlike most of the OOP languages where classes inherit classes, JavaScript Objects inherit Objects i.e. certain features (property and methods) of one object can be reused by other Objects.

Let’s understand inheritance with an example:

//Inheritance 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 for calling the above class constructor
        super(name);
        this.id = id;
    }
    toString(){
        return (`${super.toString()},Student ID: ${this.id}`);
    }
}
let student1 = new student('Ram',25);
console.log(student1.toString());

Enter fullscreen mode Exit fullscreen mode

In the above example, we define an Person Object with certain properties and methods and then we inherit the Person Object in the Student Object and use all the properties and methods of the person Object as well as define certain properties and methods for the Student Object.

Top comments (0)