JavaScript OOP
OOP is a programming paradigm that organizes code into objects, which
bundle data (properties) and behavior (methods) together.
Although JavaScript was originally prototype-based (not class-based like Java
or C++), ES6 introduced classes to make OOP easier and more familiar.
Its classes are primarily syntactic sugar over existing prototype-based
inheritance mechanisms. It provides a more familiar syntax for developers
coming from class based languages such as C++, Java etc
What is Object in OOP
Object is a collection of properties and methods
Parts of OOP
Object Literal
+ Constructor function
+ Prototypes
+ Classes
+ Instances (new, this)
4 Pillars of OOPs
Abstraction
Encapsulation
Inheritance
Polymorphism
Lets start with Object Literal
Example : [Link]
Const user ={
username: “ATU”,
loginCount : 8,
signedIn: true,
getUserDetails = function(){
[Link](“Here are the user details”);
//[Link](“Username : ${username}”) // This will give an error
// [Link](“Username : ${[Link]}”)
}
}
[Link]([Link]);
‘this’ keyword - this refers to the current object.
If we print this keyword only like [Link](this) it will give us user details
If we print this keyword in global context it will give you blank
Now lets talk about constructer function
Create one function
function User(username, loginCount, isLoggedIn){
[Link] = username;
[Link] = loginCount;
[Link] = isLoggedIn;
return this;
}
const userOne = User(“ATU”, 8, true);
//const userTwo = User(“DYP”, 12, false);
[Link](userOne);
Here when we create another user it will overwrite the values.
So we need to use constructor function which create new instance everytime
and that is keyword new
When we create new keyword it create empty object or instance
Step1: new keyword
Step2: constructor function call
Step3: arguments inject
Step4: got arguments in functions
We can have function inside function of type function expression.
Try
[Link]([Link])
Classes
ES6 introduced the class keyword. A class is a blueprint for creating objects.
class Student {
constructor(name, age) {
[Link] = name;
[Link] = age;
}
greet() {
[Link](`Hi, I'm ${[Link]} and I'm ${[Link]}
years old.`);
}
}
let s1 = new Student("Arjun", 21);
[Link](); // Hi, I'm Arjun and I'm 21 years old.
Encapsulation (Data Hiding)
Encapsulation is bundling data and methods. In JavaScript, private properties
can be simulated using closures or # private fields (ES2020).
class BankAccount {
#balance = 0; // private field
deposit(amount) {
this.#balance += amount;
[Link](`Deposited: ${amount}`);
}
getBalance() {
return this.#balance;
}
}
let acc = new BankAccount();
[Link](500);
[Link]([Link]()); // 500
// [Link](acc.#balance); ❌ Error (private)
Inheritance
Inheritance allows one class to use properties and methods of another.
class Person {
constructor(name) {
[Link] = name;
}
greet() {
[Link](`Hello, I'm ${[Link]}`);
}
}
class Student extends Person {
constructor(name, course) {
super(name); // call parent constructor
[Link] = course;
}
study() {
[Link](`${[Link]} is studying ${[Link]}`);
}
}
let s3 = new Student("Meera", "Computer Science");
[Link](); // Hello, I'm Meera
[Link](); // Meera is studying Computer Science
Polymorphism
Polymorphism allows different objects to respond differently to the same
method call.
class Animal {
sound() {
[Link]("Some generic sound");
}
}
class Dog extends Animal {
sound() {
[Link]("Bark!");
}
}
class Cat extends Animal {
sound() {
[Link]("Meow!");
}
}
Abstraction
Abstraction hides implementation details.
In JS, we can use abstract-like classes (not true abstraction, but a convention).
class Shape {
area() {
throw "Area method must be implemented!";
}
}
class Circle extends Shape {
constructor(radius) {
super();
[Link] = radius;
}
area() {
return [Link] * [Link] * [Link];
}
}
let c = new Circle(5);
[Link]([Link]()); // 78.5398...
let animals = [new Dog(), new Cat(), new Animal()];
[Link](animal => [Link]());
// Bark!
// Meow!
// Some generic sound
Prototype & Prototype Chain
In JavaScript, every object has a hidden property [[Prototype]] that refers to
another object (its prototype).
Used for inheritance.
Functions have a prototype property that is shared across instances.
function Person(name) {
[Link] = name;
}
[Link] = function() {
[Link]("Hi, I'm " + [Link]);
};
let p1 = new Person("Amit");
[Link](); // Hi, I'm Amit
this Keyword in OOP
Refers to the current object instance.
Value depends on how a function is called.
class Demo {
constructor(name) {
[Link] = name;
}
show() {
[Link]([Link]);
}
}
let d = new Demo("JS");
[Link](); // JS
Static Methods & Properties
Belong to the class itself (not objects).
class MathUtils {
static add(a, b) {
return a + b;
}
}
[Link]([Link](5, 7)); // 12