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) {
[Link] = name;
[Link] = marks;
}
display() {
[Link](`Student Name: ${[Link]}, Marks: ${[Link]}`);
}
}
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);
[Link]();
• 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
[Link]([Link]); // 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) {
[Link] = name;
[Link] = price;
}
show() {
[Link](`Product: ${[Link]}, Price: ${[Link]}`);
}
}
let p = new Product("Laptop", 45000);
[Link]();
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) {
[Link] = model;
[Link] = color;
}
start() {
[Link](`${[Link]} started in ${[Link]} color.`);
}
}
let c1 = new Car("Swift", "Red");
[Link]();
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) {
[Link] = id;
[Link] = name;
}
}
let emp1 = new Employee(101, "Scott");
• Accessing: [Link]
• Modifying: [Link] = "Jack"
• Deleting: delete [Link]
14.8 Static Variable
• Belongs to class, not object.
• Use static keyword.
class App {
static version = "1.0.0";
}
[Link]([Link]); // 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 [Link] [Link]
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";
[Link](msg);
}
}
let d = new Demo();
[Link]();
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) {
[Link] = name;
[Link] = marks;
}
display() {
[Link](`Name: ${[Link]}, Marks: ${[Link]}`);
}
}
let s1 = new Student("Surendra", 93);
[Link]();
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);
[Link]([Link]());
• We can also modify and delete methods:
[Link] = function() { return this.a * this.b; };
[Link]([Link]()); // Now multiplication
delete [Link]; // 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;
}
}
[Link]([Link](4, 5));
14.11.5 Difference Between Instance and Static Method
Feature Instance Method Static Method
Keyword No keyword static keyword
Access [Link]() [Link]()
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() {
[Link]("Engine started...");
}
}
class Car {
constructor(engine) {
[Link] = engine;
}
drive() {
[Link]("Car is ready to drive");
[Link]();
}
}
let e = new Engine();
let myCar = new Car(e);
[Link]();
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) {
[Link] = name;
[Link] = marks;
}
show() {
[Link](`Name: ${[Link]}, Marks: ${[Link]}`);
}
}
let s1 = new Student("Surendra", 93);
let s2 = new Student("Rahul", 83);
let s3 = new Student("Priyanka", 73);
[Link]();
[Link]();
[Link]();
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) {
[Link] = id;
[Link] = name;
}
getDetails() {
return this;
}
}
let emp1 = new Employee(101, "Zini");
let empDetails = [Link]();
[Link](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
}
};
[Link]([Link]);
[Link]([Link]);
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") {
[Link] = name;
[Link] = duration;
}
show() {
[Link](`Course: ${[Link]}, Duration: ${[Link]}`);
}
}
let c1 = new Course();
let c2 = new Course("JavaScript");
let c3 = new Course("Python", "4 months");
[Link]();
[Link]();
[Link]();
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() {
[Link](`Name: ${[Link]}, Marks: ${[Link]}`);
}
};
}
let s1 = createStudent("Zini", 63);
[Link]();
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) {
[Link] = 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");
[Link]([Link]); // accessing instance variable
For static members:
class Test {
static m() {
[Link]("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"};
[Link](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 [Link]()
2. Using Spread operator ...
Example:
let original = {x: 10, y: 20};
let copy1 = [Link]({}, 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() {
[Link] = 0;
}
increment() {
[Link]++;
return this;
}
show() {
[Link]([Link]);
return this;
}
}
let c = new Counter();
[Link]().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() {
[Link]("Outer class constructor");
}
static Inner = class {
constructor() {
[Link]("Inner class constructor");
}
}
}
let o = new Outer();
let i = new [Link]();
Output:
Outer class constructor
Inner class constructor
Creating Inner Class Object Inside Outer Class
class Outer {
constructor() {
[Link]("Outer class constructor");
class Inner {
constructor() {
[Link]("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() {
[Link]("Outer class constructor");
}
static Inner = class {
constructor() {
[Link]("Inner class constructor");
}
}
static Inner1 = class {
constructor() {
[Link]("Inner 1 class constructor");
}
}
}
let o = new Outer();
let i = new [Link]();
let i1 = new Outer.Inner1();
Output:
Outer class constructor
Inner class constructor
Inner 1 class constructor
Nested Inner Class
class Outer {
constructor() {
[Link]("Outer class constructor");
}
static Inner = class {
constructor() {
[Link]("Inner class constructor");
}
static InnerInner = class {
constructor() {
[Link]("InnerInner class constructor");
}
}
}
}
let o = new Outer();
let i = new [Link]();
let ii = new [Link]();
Output:
Outer class constructor
Inner class constructor
InnerInner class constructor