Chapter 16: Object Oriented Programming in JavaScript
14.1 Introduction to OOP (Object Oriented Programming)
• JavaScript is not just a scripting language; it also supports object-oriented
programming.
• OOP means writing your code in terms of real-world objects.
• It helps in reusability, modularity, and maintainability.
• In JavaScript, we use the class keyword (from ES6) to define blueprints for creating
multiple similar objects.
14.2 Class
• A class is a blueprint or template.
• It contains variables (called properties) and functions (called methods).
• Syntax:
class Student {
constructor(name, marks) {
this.name = name;
this.marks = marks;
}
display() {
console.log(`Student Name: ${this.name}, Marks: ${this.marks}`);
}
}
14.3 Object
• An object is a real-world entity created using a class.
• We create it using the new keyword.
let s1 = new Student("Surendra", 93);
s1.display();
• We can create many objects from one class:
let s2 = new Student("Rahul", 83);
let s3 = new Student("Priyanka", 73);
14.4 Reference Variable
• A variable that stores the address/reference of an object.
• Ex:
let s4 = new Student("Zini", 63); // 'zini' is reference variable
console.log(s4.name); // Accessing property using reference
14.5 this Keyword (Same as Python's self)
• this refers to current object.
• It is used to access properties and methods of the same object.
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
show() {
console.log(`Product: ${this.name}, Price: ${this.price}`);
}
}
let p = new Product("Laptop", 45000);
p.show();
14.6 Constructor
• A special method named constructor() is used for initialization.
• It is called automatically when an object is created.
class Car {
constructor(model, color) {
this.model = model;
this.color = color;
}
start() {
console.log(`${this.model} started in ${this.color} color.`);
}
}
let c1 = new Car("Swift", "Red");
c1.start();
14.7 Types of Variables
14.7.1 Instance Variable
• Declared using this inside constructor or methods.
• Belongs to each object separately.
class Employee {
constructor(id, name) {
this.id = id;
this.name = name;
}
}
let emp1 = new Employee(101, "Scott");
• Accessing: emp1.name
• Modifying: emp1.name = "Jack"
• Deleting: delete emp1.name
14.8 Static Variable
• Belongs to class, not object.
• Use static keyword.
class App {
static version = "1.0.0";
}
console.log(App.version); // No need of object
14.9 Difference between Static and Instance Variable
Feature Static Variable Instance Variable
Declared using static keyword this keyword
Belongs to Class Object
Accessed by ClassName.variable ObjectName.variable
Memory shared? Yes (shared among all) No (unique to each object)
14.10 Local Variables
• Declared inside methods.
• Can be accessed only inside that method.
class Demo {
show() {
let msg = "Hello from inside method";
console.log(msg);
}
}
let d = new Demo();
d.show();
14.11 Methods
14.11.1 What is a Method?
• A method is simply a function inside a class.
• It is used to define behavior for the object.
• It always works on object data (accessed via this).
class Student {
constructor(name, marks) {
this.name = name;
this.marks = marks;
}
display() {
console.log(`Name: ${this.name}, Marks: ${this.marks}`);
}
}
let s1 = new Student("Surendra", 93);
s1.display();
14.11.2 Types of Methods
There are mainly 2 types of methods:
1. Instance Methods
2. Static (Class) Methods
14.11.3 Instance Methods
• These methods can access instance variables using this.
• Called using object name.
class Calculator {
constructor(a, b) {
this.a = a;
this.b = b;
}
sum() {
return this.a + this.b;
}
}
let cal = new Calculator(10, 5);
console.log(cal.sum());
• We can also modify and delete methods:
cal.sum = function() { return this.a * this.b; };
console.log(cal.sum()); // Now multiplication
delete cal.sum; // Delete method
14.11.4 Static Methods
• Defined using the static keyword.
• Cannot use this to access instance variables.
• Called using class name, not object.
class MathUtil {
static multiply(x, y) {
return x * y;
}
}
console.log(MathUtil.multiply(4, 5));
14.11.5 Difference Between Instance and Static Method
Feature Instance Method Static Method
Keyword No keyword static keyword
Access ObjectName.method() ClassName.method()
Can use this? Yes No (cannot use this for object)
14.12 Passing Object from One Class to Another
• In object-oriented programming, it is common to pass one object to another class
to achieve interaction between classes.
• This helps in building complex applications by combining different class
components.
Example:
class Engine {
start() {
console.log("Engine started...");
}
}
class Car {
constructor(engine) {
this.engine = engine;
}
drive() {
console.log("Car is ready to drive");
this.engine.start();
}
}
let e = new Engine();
let myCar = new Car(e);
myCar.drive();
Explanation:
• We created an object e of the Engine class.
• We passed that object into the Car class while creating a Car object.
• The Car class used the Engine class's functionality by calling its method through the
passed object.
14.13 Creating Multiple Objects from One Class
• We can create many objects from the same class.
• Each object will have its own separate copy of the instance variables.
• They will behave independently even though they share the same class structure.
Example:
class Student {
constructor(name, marks) {
this.name = name;
this.marks = marks;
}
show() {
console.log(`Name: ${this.name}, Marks: ${this.marks}`);
}
}
let s1 = new Student("Surendra", 93);
let s2 = new Student("Rahul", 83);
let s3 = new Student("Priyanka", 73);
s1.show();
s2.show();
s3.show();
Output:
Name: Surendra, Marks: 93
Name: Rahul, Marks: 83
Name: Priyanka, Marks: 73
Real-Life Example:
• Think of a Student class like a format for ID cards.
• Each student will get an ID card printed using that format (class), but the details will
be different (object values).
14.14 Returning Object from Method
• In JavaScript, a method can also return an object.
• This is useful when we want to send an object as output from a function or method.
Example:
class Employee {
constructor(id, name) {
this.id = id;
this.name = name;
}
getDetails() {
return this;
}
}
let emp1 = new Employee(101, "Zini");
let empDetails = emp1.getDetails();
console.log(empDetails);
Explanation:
• getDetails() method returns this, which means it returns the current object.
• We can store that object in a new variable and use it later.
Real-Life Example:
• Like asking for your own ID proof. You give your own details as output.
• Useful in method chaining, logging, and cloning object behavior.
14.15 Object Inside Another Object (Nested Objects)
• Sometimes, one object can contain another object inside it.
• This is useful when building structured and hierarchical data.
Example:
let student = {
name: "Surendra",
age: 22,
address: {
city: "Cuttack",
state: "Odisha",
pin: 753001
}
};
console.log(student.name);
console.log(student.address.city);
Output:
Surendra
Cuttack
Explanation:
• student is an object with another object address inside it.
• We can access inner object properties using dot . notation.
This is called a nested object or object within object.
14.16 Constructor Overloading in JavaScript
• JavaScript does not support constructor overloading directly like Java or C++.
• But we can simulate it using default values or conditional logic inside the
constructor.
Example:
class Course {
constructor(name = "Unknown", duration = "3 months") {
this.name = name;
this.duration = duration;
}
show() {
console.log(`Course: ${this.name}, Duration: ${this.duration}`);
}
}
let c1 = new Course();
let c2 = new Course("JavaScript");
let c3 = new Course("Python", "4 months");
c1.show();
c2.show();
c3.show();
Output:
Course: Unknown, Duration: 3 months
Course: JavaScript, Duration: 3 months
Course: Python, Duration: 4 months
14.17 Object as Function Return Type( it means return an object inside the function)
• A function in JavaScript can return an object.
• This is very common in real-world apps for configuration, API response, or building
reusable object logic.
Example:
function createStudent(name, marks) {
return {
name: name,
marks: marks,
display: function() {
console.log(`Name: ${this.name}, Marks: ${this.marks}`);
}
};
}
let s1 = createStudent("Zini", 63);
s1.display();
Output:
Name: Zini, Marks: 63
Real-Life Use:
• Reusable configuration builder
• Return objects from factory functions
14.18 Difference Between Class and Object
Feature Class Object
Meaning Blueprint/Template Instance of a class
Declaration Using class keyword Using new ClassName()
Usage Defines structure and behavior Used to access and run behavior
Memory No memory until object created Allocates memory when created
Example:
class Student {
constructor(name) {
this.name = name;
}
}
let s = new Student("Surendra");
• Here, Student is a class, s is an object.
14.19 Accessing Class Members
• Members (properties and methods) of a class can be accessed in the following
ways:
For instance members:
let s1 = new Student("Rahul");
console.log(s1.name); // accessing instance variable
For static members:
class Test {
static m() {
console.log("Hello!");
}
}
Test.m(); // accessing static method
14.20 Object Comparison
• In JavaScript, two objects are not equal even if they have same content.
• They are compared by reference, not by value.
Example:
let a = {name: "Zini"};
let b = {name: "Zini"};
console.log(a === b); // false
• a and b are two different objects in memory.
14.21 Cloning Objects
• Cloning means creating exact copy of an object.
• Ways to clone:
1. Using Object.assign()
2. Using Spread operator ...
Example:
let original = {x: 10, y: 20};
let copy1 = Object.assign({}, original);
let copy2 = {...original};
14.22 Method Chaining
• When a method returns this, we can chain multiple methods together.
• It improves readability and fluency.
Example:
class Counter {
constructor() {
this.value = 0;
}
increment() {
this.value++;
return this;
}
show() {
console.log(this.value);
return this;
}
}
let c = new Counter();
c.increment().increment().show();
Output:
2
14.23 Summary
• JavaScript classes and objects bring power of OOP.
• Real-world modeling, code reusability, and structure.
• Concepts like class, object, constructor, method, static keyword, object passing,
nested object, cloning, chaining, etc., make JavaScript more powerful.
14.24 Inner Class (Nested Class)
What is Inner Class?
• If a class is written inside another class, it is called an Inner Class (or Nested Class).
• Inner class always depends on the Outer class.
• If there is no outer class, then there is no chance for the inner class to exist.
Real-Life Examples:
1. If a university doesn't exist, there’s no chance of classrooms.
2. If a laptop doesn’t exist, there is no processor.
3. If a book doesn’t exist, there are no chapters.
4. If a person doesn't exist, there are no hands, legs, etc.
5. If a bike doesn’t exist, there is no engine.
Syntax of Inner Class
class Outer {
constructor() {
console.log("Outer class constructor");
}
static Inner = class {
constructor() {
console.log("Inner class constructor");
}
}
}
let o = new Outer();
let i = new Outer.Inner();
Output:
Outer class constructor
Inner class constructor
Creating Inner Class Object Inside Outer Class
class Outer {
constructor() {
console.log("Outer class constructor");
class Inner {
constructor() {
console.log("Inner class constructor");
}
}
let i = new Inner();
}
}
let obj = new Outer();
Output:
Outer class constructor
Inner class constructor
Outer Class with Multiple Inner Classes
class Outer {
constructor() {
console.log("Outer class constructor");
}
static Inner = class {
constructor() {
console.log("Inner class constructor");
}
}
static Inner1 = class {
constructor() {
console.log("Inner 1 class constructor");
}
}
}
let o = new Outer();
let i = new Outer.Inner();
let i1 = new Outer.Inner1();
Output:
Outer class constructor
Inner class constructor
Inner 1 class constructor
Nested Inner Class
class Outer {
constructor() {
console.log("Outer class constructor");
}
static Inner = class {
constructor() {
console.log("Inner class constructor");
}
static InnerInner = class {
constructor() {
console.log("InnerInner class constructor");
}
}
}
}
let o = new Outer();
let i = new Outer.Inner();
let ii = new Outer.Inner.InnerInner();
Output:
Outer class constructor
Inner class constructor
InnerInner class constructor