Object-Oriented JavaScript

Sheikh Mohammad Nazmul H.
4 min readFeb 4, 2024

--

  1. What is OOP?

Object-oriented programming is a programming paradigm based on the concept of “objects”, which can contain data, in the form of fields, and code, in the form of procedures.

Three core concept of OOP is:

i) Encapsulation

ii) inheritance

iii) Polymorphism

2. Encapsulation:

Sometimes we need to secure some information or do not want to direct access to some information or some object components in that case we use encapsulation. It also bundling data with methods that operate in that data.

Why encapsulation:

i) Security — controlled access.

ii)Hide implementation and expose behaviour.

iii)Loose coupling — modify the implementation anytime.

Example:

function Photo(name){

this.name = name || “photo” ;

}

Photo.prototype.setName = function(name) {

this.name = name;

}

Photo.prototype.getName = function() {

return this.name;

};

var photo = new Photo();

photo.setName(“picture”); //sets photo name to “picture”

photo.getName(); //return “picture”

3. Inheritance:

In object-oriented programming languages like c# and java to implement inheritance, a class inherits from another class. In JavaScript, we don’t have the concept of classes, so inheritance in javascript is prototype-based. This means to implement inheritance in JavaScript, an object inherits from another object.

Why Inheritance:

i) Inheritance promotes reusability. When a class inherits or derives another class, it can access all the functionality of the inherited class.

ii) Inheritance helps to reduce code redundancy and supports code extensibility.

iii) Inheritance facilitates the creation of class libraries.

Example:

function Student(firstName, lastName, schoolName, grade)

{

Person.call(this, firstName, lastName);

this.SchoolName = schoolName || “unknown”;

this.Grade = grade || 0;

}

//Student.prototype = Person.prototype;

Student.prototype = new Person();

Student.prototype.constructor = Student;

4. Polymorphism:

Poly = many, Morph = forms . So Polymorphism = many forms o representing something in different forms.

Why Polymorphism:

i) It helps programmers reuse the code and classes once written, tested, and implemented. They can be reused in many ways.

ii) A single variable name can be used to store variables of multiple data types(Float, double, Long, Int, etc).

iii) Polymorphism helps in reducing the coupling between different functionalities.

Example:

var answer ={

get: function fn1() {

return this.val;

},

val: 42

};

var firmAnswer = Object.create(answer);

firmAnswer.get = function fn2() {

return this.val + “!!”;

};

answer.get(); //42

firmAnswer.get();// “42!!”

5.Functions as objects:

n JavaScript, functions are objects. You can work with functions as if they were objects. For example, you can assign functions to variables, to array elements, and to other objects. They can also be passed around as arguments to other functions or be returned from those functions.

Example:

function message() {

alert(“Greetings Linda!”);

}

alert(typeof message); // => function

alert(message instanceof Object); // => true

6. Prototype objects:

Prototype objects are a simpler approach for adding new methods/properties to a constructor function.

Example:

var Shape={

name: ‘Rectangle’,

sides: 4

}

//Rectangle object

var Rectangle = {

length: 3,

width: 5

}

//setting [[Prototype]] of Rectangle equal to Shape

Rectangle.__proto__ = Shape

//creating an object instance using Shape and Rectangle

console.log(“Name of shape is:”,Rectangle.name)

console.log(“Number of sides are”,Rectangle.sides)

console.log(“Length is:”,Rectangle.length)

console.log(“Width is:”,Rectangle.width)

7.Immutability:

Immutability means that change is not done on the same object, structure, but change is represented in a new one. And this is because reference represents value not only memory pointer. … Functions are safe to use because instead of mutation, they deal with their own versions with their own values.

Example:

let heightRequirement = 46;

function canRide(height) {

return height >= heightRequirement;

} // Every half second, set heightRequirement to a random number between 0 and 200.

setInterval(() => heightRequirement = Math.floor(Math.random() * 201), 500);

const mySonsHeight = 47; // Every half second, check if my son can ride.

// Sometimes it will be true and sometimes it will be false.

setInterval(() => console.log(canRide(mySonsHeight)), 500);

8. Recursion:

Recursion is a technique for iterating over an operation by having a function call itself repeatedly until it arrives at a result. Most loops can be rewritten in a recursive style, and in some functional languages this approach to looping is the default.

Example:

function iterativeFactorial(n) {

let product = 1;

for (let i = 1; i <= n; i++) {

product *= i;

}

return product;

}

9. Object literal:

Create a new object in JavaScript by setting its properties inside curly braces. Object literals property values can be any data types, like function literals, arrays, strings, numbers, or boolean.

Example:

const book = {
title: “OOP”,
author: “Nazmul”,
year: “2024”
}

10. Object constructor:

Object constructor is the same as a regular function. It will be called each time an object is created. We can use them with the new keyword. Object constructor is useful when we want to create multiple objects with the same properties and methods.

Example:

const book = {
title: “OPP”,
author: “Nazmul”,
year: “2024”
}

const book1 = {
title: “Sheikh”,
author: “Nazmul”,
year: “2024”,
}

If we want to create multiple book objects we have to duplicate the code for each book. We can keep creating books but it’s kind of a pain — the object constructor helps us to reuse the object literal.

function Book(title, author, year) {
this.title = title;
this.author = author;
this.year = year;
}const book1 = new Book (‘Endgame’, ‘Kumu, ‘2024’);

console.log(book1);
> Book {
title: “Endgame“,
author: “Sheikh”,
year: “2020”
}// if we want to create more than one book just we call function book with new keyword.const book2 = new Book (‘Day-6’, ‘Kumu’, ‘2020’);

book1 and book2 create an instance of Book and assigned it to a variable. To find out whether an object is an instance of another one. We can use intanceof.

book1 instanceof Book
> true

--

--