0% found this document useful (0 votes)
4 views

Lecture 11 - Classes & Objects

Uploaded by

muhammad.ayub85
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lecture 11 - Classes & Objects

Uploaded by

muhammad.ayub85
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Understanding JavaScript: Objects, Prototypes, and Classes

Objects in JavaScript
 What is a JavaScript object?
A JavaScript object is an entity with:
o State: These are the object's properties (e.g., a car's color or speed).
o Behavior: These are the object's methods (e.g., a car can drive).
 Why is it called an Entity?
An entity has:
o State: The properties that hold data.
o Behavior: The methods that define actions the object can do.
 Example:
o A car is an entity (JavaScript object):
 State: Properties like brand, model, and year.
 Behavior: A method like startEngine().
 Summary:
An entity in JavaScript is simply an object with both properties (state) and methods
(behavior), which allows it to store information and perform actions.

2. Prototypes in JavaScript
 Definition: Every object in JavaScript has a prototype.
o Purpose: A prototype is another object that shares properties and methods.
o How It Works:
 If an object doesn't have a property or method, JavaScript looks at its
prototype to find it
 This process continues up the prototype chain until it finds the property or
method, or until it runs out of prototypes.

3. How Prototypes Help


 Inheritance: Objects can inherit properties and methods from other objects via
prototypes.
o This avoids repeating the same code in multiple objects.

4. Classes in JavaScript
 Definition: A class is like a blueprint to create objects.
o Purpose: It defines what an object should have (properties) and what it should do
(methods).
 How It Works:
o We can create many objects from one class, each with their own values but the
same behavior.

5. Why Use Prototypes and Classes?


 Prototypes: Help save memory by allowing multiple objects to share the same
methods.
 Classes: Provide a clean way to create many similar objects with consistent properties
and actions.

Summary:
 Object: A specific thing with properties and methods (e.g., a car).
 Prototype: A special object that allows sharing properties and methods.
 Class: A blueprint for creating multiple similar objects.

1. Understanding JavaScript Objects


An object in JavaScript is like a container that holds:
 Properties (Variables): These describe the state or characteristics of the object
(e.g., color, speed of a car).
 Methods (Functions): These describe the behavior or actions of the object (e.g.,
drive or stop the car).

2. The Prototype Feature


Every object in JavaScript has a special property called prototype.
 Prototype allows objects to inherit properties and methods from other objects.
 You can access and link an object's prototype using __proto__.
 If an object has the same method as its prototype, the object will use its own method,
not the prototype's.

3. What is a Prototype?
A prototype is a "toolbox" that an object can use to borrow features (like methods or
values) from another object.

4. How Prototypes Work


When an object has a prototype:
 It can use whatever the prototype offers (like a helper or shared features).
 Think of it as borrowing tools that are not directly part of the object.

5. Example: Prototypes in Action


Let’s look at two objects: car and sportsCar.
1. We make sportsCar use car as a prototype.
2. Now, sportsCar can use the properties and methods of car.
Think of the prototype as a “toolbox” that sportsCar can use.

6. Understanding Prototype in JavaScript


 Prototype in JavaScript helps objects and functions share common properties and
methods.
 It works as a template or blueprint, which makes the code more efficient by
reducing repetition.

7. How Does Prototype Work?


Prototype Chain
 JavaScript first looks for a property or method in the object itself.
 If not found, it checks the object’s prototype.
 This continues until JavaScript finds what it’s looking for or runs out of places to check.
Inheritance
 Objects can inherit properties and methods from other objects through prototypes.
 This is important in object-oriented programming.

8. Key Points About Prototype


 Every function in JavaScript has a prototype property.
 When you create a new object from a function, the object can use that function’s
prototype.
 If you add properties or methods to a function’s prototype, all objects created from
that function can use them.

9. Example: Using Prototypes


// Function to create car objects
function Car(make, model) {
this.make = make; // The make of the car
this.model = model; // The model of the car
}
// Adding a method to the Car prototype
Car.prototype.getDetails = function() {
return `${this.make} ${this.model}`;
};
// Creating new car objects
let car1 = new Car('Toyota', 'Corolla');
let car2 = new Car('Honda', 'Civic');
// Using the prototype method
console.log(car1.getDetails()); // Output: Toyota Corolla
console.log(car2.getDetails()); // Output: Honda Civic
Explanation:
 Car Function: It creates new car objects.
 Prototype Method: getDetails() is added to the Car.prototype, so all car objects can
use it.
 Sharing Through Prototype: Both car1 and car2 use the getDetails method from
the prototype.

10. Why Use Prototype?


 Memory efficiency: Methods don’t need to be repeated in each object.
 Adding new methods: You can add methods to all objects at once without changing
the original function.

11. Conclusion on Prototypes


Prototypes allow objects to share properties and methods, making your JavaScript code
cleaner and more efficient.

12. How to Create Objects in JavaScript


Here are different ways to create objects:
1. Object Literal ({}): The simplest way to create an object.
2. new Object(): Creates an object using the Object constructor (less common).
3. Constructor Function: A function used to create multiple objects with similar
properties.
4. Class (ES6): A modern and structured way to create objects.
5. Object.create(): Creates an object with a specified prototype.
6. Object.assign(): Copies properties from one or more source objects into a target
object.

13. Writing a Simple Class


Here’s how to create a class in JavaScript:
class MyClass {
constructor() {
// Constructor code here
}
myMethod() {
// Method code here
}
}
let myObj = new MyClass(); // Creating an object from the class
Explanation:
 class MyClass: Defines a class named MyClass.
 constructor(): A special method that runs when a new object is created, used to
initialize the object.
 myMethod(): A method that belongs to the class, and can be called on objects
created from it.
 let myObj = new MyClass(): Creates a new object myObj from the MyClass class.

14. Objects and Classes in JavaScript


1. Using an Object in JavaScript
An object holds all the details about one specific thing (like a car).
const car = {
color: "red",
model: "Toyota",
speed: 120,
drive: function() {
console.log("The car is driving.");
}
};
// Accessing the car's details
console.log(car.color); // red
console.log(car.model); // Toyota
car.drive(); // The car is driving.
Explanation:
 car is an object with properties (color, model, speed) and a method (drive()).
 You can access these properties and use the methods to describe and perform actions
related to the car.

2. Using a Class in JavaScript


A class helps you create many objects with the same properties and behaviors.
class Car {
constructor(color, model, speed) {
this.color = color;
this.model = model;
this.speed = speed;
}
drive() {
console.log("The car is driving.");
}
}
// Create new car objects using the Car class
const car1 = new Car("red", "Toyota", 120);
const car2 = new Car("blue", "Honda", 130);
// Accessing car details
console.log(car1.color); // red
console.log(car2.model); // Honda
car1.drive(); // The car is driving.
Explanation:
 Car class: A blueprint to create car objects.
 Constructor: Sets the car’s color, model, and speed.
 Method drive(): Describes the behavior of the car.

15. Summary with Car Example


 Object: Represents a single car, with specific properties and behaviors.
 Class: A template or blueprint to create multiple cars with the same properties and
behaviors.

16. Simple Explanation: Objects vs Classes


 Object: Like a single car with specific details (color, model, speed).
 Class: Like a factory or blueprint that helps you create many cars with similar details
and actions.

17. Final Analogy


 A class is like a mold that defines how something (like a toy) should be made.
 The objects are the toys you create from that mold.
 You can use the same mold (class) to create as many toys (objects) as you need, but
you can adjust things like color or size.

Conclusion
 Class: A template for creating objects.
 Object: The actual item created using the template (class).
 Prototype: A shared toolbox that allows objects to inherit properties and methods
from other objects, saving memory and making code cleaner.

Understanding the Relationship Between Objects, Prototypes, and Classes in


JavaScript
JavaScript uses a unique way to handle objects, which can sometimes be confusing for
beginners. Let's break down the concepts of objects, prototypes, and classes in simple
terms.

1. Objects in JavaScript
 What are Objects?
o Objects are collections of properties (key-value pairs).
o They can store data (like variables) and functions (called methods).
 How to Create an Object
const car = {
brand: "Toyota",
model: "Corolla",
start: function() {
console.log("Car is starting...");
}
};
o Here, car is an object with properties (brand, model) and a method (start()).
2. Prototypes in JavaScript
 What are Prototypes?
o Every JavaScript object has a hidden property called __proto__, which points to
another object called its prototype.
o Prototypes allow objects to inherit properties and methods from other objects.
 How Prototypes Work
const animal = {
sound: "Roar",
makeSound: function() {
console.log(this.sound);
}
};
const lion = {};
lion.__proto__ = animal; // lion inherits from animal
lion.makeSound(); // Output: Roar
o lion doesn't have its own makeSound method, so it looks up to its prototype
(animal) for that method.

3. Classes in JavaScript
 What are Classes?
o Classes are a way to create objects with a blueprint.
o They are like templates for creating multiple objects with similar properties and
methods.
o Introduced in ES6 (2015), they make JavaScript more structured.
 How to Create a Class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}.`);
}
}
const john = new Person("John", 30);
john.greet(); // Output: Hello, my name is John.
o Person is a class. We use new to create objects (instances) from this class.
o The greet method is shared by all instances of Person via the prototype.

Relationship Between Objects, Prototypes, and Classes


1. Objects are individual entities that hold data and behavior.
2. Prototypes are objects that other objects can use as a reference to inherit properties
and methods.
3. Classes are templates for creating objects, making it easier to structure and organize
code. Under the hood, classes still use prototypes for inheritance.

Conclusion
 Objects are fundamental building blocks.
 Prototypes provide a way for objects to share behavior and properties.
 Classes offer a cleaner, more structured way to create objects, especially when you
need multiple similar objects.
This hierarchy makes JavaScript flexible and powerful, allowing developers to use different
patterns for creating and managing objects.

You might also like