0% found this document useful (0 votes)
1 views25 pages

Lecture JS - Objects - Part 2

The document explains object-oriented programming (OOP) in JavaScript, highlighting the use of objects, properties, and methods. It covers various techniques for creating objects, including basic objects, constructor functions, and modern class syntax, as well as key OOP concepts such as inheritance, encapsulation, and polymorphism. The document provides examples to illustrate these concepts and their implementation in JavaScript.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views25 pages

Lecture JS - Objects - Part 2

The document explains object-oriented programming (OOP) in JavaScript, highlighting the use of objects, properties, and methods. It covers various techniques for creating objects, including basic objects, constructor functions, and modern class syntax, as well as key OOP concepts such as inheritance, encapsulation, and polymorphism. The document provides examples to illustrate these concepts and their implementation in JavaScript.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Object-Oriented Programming in

JavaScript
In JavaScript, object-oriented programming (OOP) is a programming paradigm that is based on
the concept of objects. These objects can contain properties (which are key-value pairs) and
methods (functions that belong to the object). JavaScript allows you to work with objects and
create classes (templates for objects) using both older and newer techniques.
Basic Objects in JavaScript
IN JAVASCRIPT, OBJECTS ARE SIMPLY COLLECTIONS OF
PROPERTIES AND METHODS. HERE’S A BASIC EXAMPLE:
// Defining an object
const car = {
make: "Toyota",
model: "Corolla",
year: 2021,
displayInfo: function() {
console.log(`${this.year} ${this.make} ${this.model}`);
}
};

// Accessing object properties


console.log(car.make); // "Toyota"
car.displayInfo(); // "2021 Toyota Corolla"
In the example above:make, model, and year are properties of the car object.
displayInfo is a method that displays the car's information.
Constructor Functions (Old Style of Creating
Objects)
BEFORE JAVASCRIPT INTRODUCED CL ASSES,
CONSTRUCTOR FUNCTIONS WERE USED TO CREATE
OBJECTS WITH THE S AME STRUCTURE.
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.displayInfo = function() {
console.log(`${this.year} ${this.make} ${this.model}`);
};
}

// Creating an object using the constructor function


const myCar = new Car("Honda", "Civic", 2020);
myCar.displayInfo(); // "2020 Honda Civic"
Using Classes (Modern OOP in JavaScript)
JAVASCRIPT ES6 INTRODUCED THE CL ASS SYNTAX,
WHICH IS A MORE FORMAL AND READABLE WAY OF
DEFINING OBJECTS AND THEIR BEHAVIOR.
class Car {
// Constructor method
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}

// Method
displayInfo() {
console.log(`${this.year} ${this.make} ${this.model}`);
}
}

// Creating an instance of the class


const myCar = new Car("Ford", "Focus", 2022);
myCar.displayInfo(); // "2022 Ford Focus"
In the above example:constructor is a special method used to initialize objects created from
the class.
displayInfo is a method that belongs to all instances of the Car class.
Inheritance in JavaScript (Using extends)
JAVASCRIPT SUPPORTS INHERITANCE, WHICH ALLOWS
YOU TO CREATE A NEW CL ASS BASED ON AN EXISTING
ONE. THIS IS ACHIEVED USING THE EXTENDS KEYWORD.
class Vehicle {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
displayInfo() {
console.log(`${this.year} ${this.make} ${this.model}`);
}
}
// Car class inherits from Vehicle
class Car extends Vehicle {
constructor(make, model, year, doors) {
super(make, model, year); // Calling the parent class constructor
this.doors = doors;
}
displayCarInfo() {
this.displayInfo();
console.log(`This car has ${this.doors} doors.`);
}
}
const myCar = new Car("Nissan", "Altima", 2023, 4);
myCar.displayCarInfo();
// "2023 Nissan Altima"
Here:Car inherits from the Vehicle class using extends.
super() is used to call the parent class's constructor and methods.
Encapsulation
ENCAPSUL ATION IS ABOUT KEEPING THE INTERNAL
WORKINGS OF AN OBJECT HIDDEN FROM THE OUTSIDE
WORLD. IN JAVASCRIPT, YOU CAN USE METHODS TO
CONTROL ACCESS TO PROPERTIES.
class Account {
constructor(owner, balance = 0) {
this.owner = owner;
this._balance = balance; // Conventionally, this is treated as a private property
}
deposit(amount) {
if (amount > 0) {
this._balance += amount;
}
}
withdraw(amount) {
if (amount > 0 && this._balance >= amount) {
this._balance -= amount;
}
}
getBalance() {
return this._balance;
}
}
const myAccount = new Account("John");
myAccount.deposit(100);
myAccount.withdraw(50);
console.log(myAccount.getBalance()); // 50
In this example: The balance property is considered private by convention (denoted with an
underscore).
Methods like deposit, withdraw, and getBalance control how this property is accessed and
modified.
Polymorphism
P O LY MO R P HIS M ALLO W S DIFFE R E N T C L AS S E S T O H AVE ME T HO DS
W IT H T HE S AME N AME B U T P O T E N T IALLY D IFFE R E N T
IMP LE ME N TAT I O N S . IN JAVAS C R IP T , T H IS C AN B E AC H IE VE D
T H R O U G H ME T HO D OV E R R ID IN G .
class Animal {
speak() {
console.log("Animal makes a sound");
}
}
class Dog extends Animal {
speak() {
console.log("Dog barks");
}
}
class Cat extends Animal {
speak() {
console.log("Cat meows");
}
}
const dog = new Dog();
const cat = new Cat();

dog.speak(); // "Dog barks"


cat.speak(); // "Cat meows"
In this case, Dog and Cat both override the speak method from the Animal class, allowing for
different behavior.
Class vs prototype
class Complex {
constructor(real, imag) {
this.real = real;
this.imag = imag;
}

// Add another complex number


add(other) {
return new Complex(this.real + other.real, this.imag + other.imag);
}

// Subtract another complex number


subtract(other) {
return new Complex(this.real - other.real, this.imag - other.imag);
}

// Multiply by another complex number


multiply(other) {
return new Complex(
this.real * other.real - this.imag * other.imag,
this.real * other.imag + this.imag * other.real
);
}
// Divide by another complex number
divide(other) {
const denominator = other.real ** 2 + other.imag ** 2;
return new Complex(
(this.real * other.real + this.imag * other.imag) / denominator,
(this.imag * other.real - this.real * other.imag) / denominator
);
}

// Absolute value (magnitude)


abs() {
return Math.hypot(this.real, this.imag);
}

// String representation
toString() {
const sign = this.imag >= 0 ? '+' : '-';
return `${this.real} ${sign} ${Math.abs(this.imag)}i`;
}
}
// Example usage:

const c1 = new Complex(2, 3);

const c2 = new Complex(1, -4);

console.log('c1 + c2 =', c1.add(c2).toString()); // "3 - 1i"

console.log('c1 - c2 =', c1.subtract(c2).toString()); // "1 + 7i"

console.log('c1 * c2 =', c1.multiply(c2).toString()); // "14 - 5i"

console.log('c1 / c2 =', c1.divide(c2).toString()); // "-0.6470588235294118 + 0.47058823529411764i"

console.log('|c1| =', c1.abs()); // 3.60555127546


// Add conjugate method to prototype

Complex.prototype.conj = function() {

return new Complex(this.real, -this.imag);

};

// Usage

const c = new Complex(3, 4);

console.log(c.toString()); // "3 + 4i"

console.log(c.conj().toString()); // "3 - 4i"


Conclusion
Object-oriented programming in JavaScript can be done using:
•Basic objects
•Constructor functions (older way)
•Classes (ES6+ modern syntax)
•Features like inheritance, encapsulation, and polymorphism are also supported.

You might also like