[Go to site: main page, start]

0% found this document useful (0 votes)
6 views22 pages

JavaScript Inheritance & Prototype Basics

This document provides an overview of JavaScript inheritance, the prototype chain, and the differences between frontend and backend JavaScript. It explains prototype-based inheritance with examples, the structure of HTTP requests and responses, and common HTTP status codes. Additionally, it covers the use of the Fetch API for making HTTP requests in JavaScript.

Uploaded by

Mishita Ingawale
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views22 pages

JavaScript Inheritance & Prototype Basics

This document provides an overview of JavaScript inheritance, the prototype chain, and the differences between frontend and backend JavaScript. It explains prototype-based inheritance with examples, the structure of HTTP requests and responses, and common HTTP status codes. Additionally, it covers the use of the Fetch API for making HTTP requests in JavaScript.

Uploaded by

Mishita Ingawale
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JavaScript Lesson: Inheritance, Prototype Chain & Frontend-Backend

Concepts

🔹 1. Introduction to Inheritance in JavaScript


📘 Definition:
Inheritance allows one object to use the properties and methods of another
object.
It promotes code reuse, modularity, and readability.
JavaScript uses a prototype-based inheritance model, not class-based (like
Java or C++).

🔸 Example (Before ES6 – Prototype-based):


function Animal(name) {
[Link] = name;
}

[Link] = function() {
[Link]([Link] + ' makes a sound.');
};

function Dog(name) {
[Link](this, name); // inherit properties
}

[Link] = [Link]([Link]); // inherit methods


[Link] = Dog;

1
[Link] = function() {
[Link]([Link] + ' barks.');
};

let dog1 = new Dog('Tommy');


[Link](); // Output: Tommy barks.
Explanation:
 Animal is the parent (superclass).
 Dog is the child (subclass).
 The line [Link]([Link]) links Dog to Animal's prototype
chain.
 The constructor property is reset back to Dog.

🔸 Example (ES6 Class Syntax – Cleaner way):


class Animal {
constructor(name) {
[Link] = name;
}

speak() {
[Link](`${[Link]} makes a sound.`);
}
}

class Dog extends Animal {


speak() {

2
[Link](`${[Link]} barks.`);
}
}

let d = new Dog('Rocky');


[Link](); // Output: Rocky barks.
Explanation:
 extends keyword is used for inheritance.
 super() calls the parent class constructor.
 ES6 class syntax is syntactic sugar over prototype-based inheritance.

🔹 2. Understanding the Prototype Chain


📘 Definition:
Every JavaScript object has a hidden property called [[Prototype]] (accessed
using __proto__), which refers to another object.
If a property or method is not found in the object, JavaScript looks for it up the
prototype chain.

🔸 Example:
let person = {
greet() {
[Link]("Hello!");
}
};

let student = [Link](person);


[Link] = function() {

3
[Link]("Studying...");
};

[Link](); // Output: Hello!


[Link](); // Output: Studying...
Explanation:
 student’s prototype points to person.
 When [Link]() is called, it’s not found in student, so JavaScript
checks person.
 This upward search forms the prototype chain.

🔸 Prototype Chain Visualization:


student --> person --> [Link] --> null
Each object inherits properties from the one above it, until reaching null.

🔹 3. Prototype Implementation (Manually Creating Prototypes)


You can directly attach methods to an object’s prototype to make them
available to all instances.
🔸 Example:
function Car(brand, model) {
[Link] = brand;
[Link] = model;
}

// Adding a method to Car's prototype


[Link] = function() {
[Link](`${[Link]} ${[Link]} is starting...`);

4
};

let car1 = new Car("Toyota", "Innova");


let car2 = new Car("Honda", "City");

[Link](); // Output: Toyota Innova is starting...


[Link](); // Output: Honda City is starting...
Why use prototype methods?
 Saves memory.
 The method is stored once in the prototype, not duplicated across all
objects.

🔸 Checking Prototypes:
[Link](car1.__proto__ === [Link]); // true
[Link]([Link].__proto__ === [Link]); // true

🔸 Built-in Prototypes:
All JavaScript objects inherit from built-in prototypes:
 [Link]
 [Link]
 [Link]
 [Link], etc.
You can even extend these prototypes (carefully).
Example:
[Link] = function() {
return [Link]('').reverse().join('');
};

5
[Link]("hello".reverse()); // Output: olleh

🔹 4. Understanding Frontend and Backend


📘 JavaScript on Frontend:
 Runs in the browser.
 Controls User Interface (UI) and interactivity.
 Works with HTML & CSS to handle dynamic content.
Example (Frontend JS):
<button Me</button>

<script>
function showMessage() {
alert("Hello from Frontend JavaScript!");
}
</script>

📘 JavaScript on Backend:
 Runs on the server using [Link].
 Handles database queries, API creation, and server logic.
Example (Backend JS using [Link]):
const http = require('http');

const server = [Link]((req, res) => {


[Link](200, {'Content-Type': 'text/plain'});
[Link]('Hello from Backend JavaScript!');
});
6
[Link](3000, () => {
[Link]('Server running on [Link]
});

🔸 Frontend vs Backend (Comparison Table)


Feature Frontend Backend
Runs on Browser Server
Languages HTML, CSS, JavaScript [Link], Python, PHP, Java
Role UI and User Interaction Logic, Database, APIs
Example Button click, form validation Saving data, authentication

🔹 5. Summary
Concept Key Idea Example
Reusing properties/methods class Dog extends
Inheritance
from parent class Animal
Mechanism by which objects
Prototype Chain [Link](parent)
inherit features
Prototype Adding reusable methods to
[Link] = ...
Implementation prototype
Frontend JavaScript on client/browser DOM manipulation
Handling HTTP
Backend JavaScript on server ([Link])
requests

✅ Quick Quiz
1. What is prototype inheritance?
2. What is the purpose of the super() keyword?

7
3. What does [Link]() do?
4. Name one difference between frontend and backend JavaScript.
5. What will this print?
6. function A() {}
7. [Link] = function() { [Link]("Hello"); }
8. let obj = new A();
9. [Link]();
👉 Output: Hello

8
What Is Prototyping in JavaScript?

🔹 1. Basic Idea
Every JavaScript object has a hidden internal link to another object called its
prototype.
This prototype object is like a blueprint that defines shared properties and
methods for all instances of a given object type.
💡 In other words:
Prototyping is a mechanism in JavaScript that allows objects to inherit features
(methods and properties) from other objects.

🔹 2. Why Do We Use Prototypes?


Imagine you create 100 Car objects — all need a start() method.
If you define the start() function inside every Car, it will waste memory because
the same function will be duplicated 100 times.
Using prototypes, we can define start() only once — and all Car objects will
share it.

Example 1 — Without Prototype:


function Car(brand, model) {
[Link] = brand;
[Link] = model;
[Link] = function() { // defined for each object separately ❌
[Link]([Link] + " " + [Link] + " is starting...");
};
}

let car1 = new Car("Toyota", "Innova");


let car2 = new Car("Honda", "City");

9
[Link]([Link] === [Link]); // false ❌ (two copies)

Example 2 — With Prototype:


function Car(brand, model) {
[Link] = brand;
[Link] = model;
}

// Add shared method to prototype ✅


[Link] = function() {
[Link]([Link] + " " + [Link] + " is starting...");
};

let car1 = new Car("Toyota", "Innova");


let car2 = new Car("Honda", "City");

[Link]([Link] === [Link]); // true ✅ (one shared method)


Explanation:
All objects created from Car share the same start() function through
[Link].

🔹 3. The Prototype Chain


When you access a property or method of an object:
1. JavaScript first looks inside the object itself.
2. If not found, it looks up the prototype chain — i.e., the object’s
prototype.

10
3. If not found there, it goes up to [Link].
4. Finally, if still not found → returns undefined.

Example:
let student = {
name: "Aarav"
};

let person = {
greet() {
[Link]("Hello!");
}
};

student.__proto__ = person; // set person as prototype of student

[Link](); // Output: Hello!


How it works internally:
1. JS looks for greet() in student → not found.
2. Then goes to student.__proto__ → finds [Link]() → executes it.

Prototype Chain Visualization:


student --> person --> [Link] --> null

🔹 4. Built-in Prototypes
Every built-in object type (Array, Function, String, Date, etc.) has its own
prototype, which provides common methods.

11
Example:
let arr = [1, 2, 3];

[Link](arr.__proto__ === [Link]); // true


[Link]([Link].__proto__ === [Link]); // true

🔹 5. Extending Built-in Prototypes (⚠️Use with Caution!)


You can add custom methods to built-in prototypes, but it’s not recommended
for production (may cause conflicts).
Example:
[Link] = function() {
return [Link]('').reverse().join('');
};

[Link]("hello".reverse()); // Output: olleh

🔹 6. Prototype in ES6 Classes


Even when you use the modern class syntax, JavaScript still uses prototypes
under the hood.
Example:
class Animal {
speak() {
[Link]("Animal speaks");
}
}

let dog = new Animal();

12
[Link]([Link](dog) === [Link]); // true
So, class syntax is just syntactic sugar for prototype-based inheritance.

🔹 7. Key Prototype-Related Properties and Methods


Property / Method Description
__proto__ Points to the prototype of the object
[Link](obj) Returns the prototype of obj
[Link](proto) Creates a new object with the given prototype
Checks if property belongs directly to object (not
hasOwnProperty()
prototype)

Example:
let car = { brand: "Toyota" };
let sportsCar = [Link](car);
[Link] = "Supra";

[Link]([Link](sportsCar)); // { brand: 'Toyota' }


[Link]([Link]('model')); // true
[Link]([Link]('brand')); // false (inherited)

🧩 Summary
Concept Explanation
An object that serves as a template from which other
Prototype
objects inherit properties and methods.
A hierarchy where an object inherits from its prototype,
Prototype Chain
which in turn may inherit from another.

13
Concept Explanation
Prototype Mechanism where objects share behavior through their
Inheritance prototypes.
ES6 Classes Cleaner syntax for prototype-based inheritance.

✅ Key Takeaways
 JavaScript uses prototypal inheritance, not classical inheritance.
 Every object has a prototype, which may itself have another prototype.
 Methods added to a constructor’s prototype are shared by all its
instances.
 The prototype chain ends with [Link], whose prototype is null

14
Lesson: HTTP Request and Response

🔹 1. Introduction to HTTP
📘 What is HTTP?
HTTP (HyperText Transfer Protocol) is the communication protocol used
between a client (usually a browser) and a web server.
It defines how messages are formatted and transmitted, and how servers and
browsers should respond to various commands.
Every time you open a website, your browser sends an HTTP Request to the
server, and the server sends back an HTTP Response.

🔸 Example:
When you visit
👉 [Link]
 The browser (client) sends an HTTP Request to the web server asking for
[Link].
 The server processes it and sends an HTTP Response containing the
HTML page.

📈 HTTP = Request + Response Cycle


Client (Browser) Server
───────────────────────▶ HTTP Request (GET /[Link])
◀──────────────────────
HTTP Response (HTML Page)

🔹 2. HTTP Request
📘 What is an HTTP Request?
An HTTP request is a message sent by the client to the server to perform an
action — such as fetching a webpage, submitting a form, or uploading data.

15
🔸 Structure of an HTTP Request:
1. Request Line
o Contains: Method, URL, and HTTP version
o Example:
o GET /[Link] HTTP/1.1
2. Headers
o Provide additional info about the request (like browser type,
accepted formats, etc.)
o Example:
o Host: [Link]
o User-Agent: Mozilla/5.0
o Accept-Language: en-US
3. Body (Optional)
o Contains data sent from client to server (mainly in POST requests)
o Example:
o {
o "username": "john",
o "password": "12345"
o }

🔸 Common HTTP Request Methods


Method Description Example Use
GET Retrieve data from the server Fetching a webpage
POST Send data to the server Submitting a form
PUT Update existing data Editing a profile
DELETE Remove data Deleting an item
16
Method Description Example Use

PATCH Partially update data Change user email only


HEAD Fetch headers only Check resource availability

🔸 Example Request (GET)


GET /products HTTP/1.1
Host: [Link]
User-Agent: Chrome/120.0
Accept: application/json
🔸 Example Request (POST)
POST /login HTTP/1.1
Host: [Link]
Content-Type: application/json

{
"email": "user@[Link]",
"password": "secret"
}

🔹 3. HTTP Response
📘 What is an HTTP Response?
An HTTP Response is the message sent by the server back to the client after
processing a request.

🔸 Structure of an HTTP Response:


1. Status Line

17
o Contains: HTTP version, Status Code, Status Message
o Example:
o HTTP/1.1 200 OK
2. Response Headers
o Provide details about the response (content type, date, length,
etc.)
o Example:
o Content-Type: text/html
o Content-Length: 2048
o Server: Apache
3. Body
o Contains the requested resource (HTML, JSON, file, etc.)
o Example:
o <html>
o <body>
o <h1>Welcome!</h1>
o </body>
o </html>

🔹 4. HTTP Status Codes


These indicate the result of the client’s request.
Category Code Range Meaning
Informational 100–199 Request received, continuing
Success 200–299 Request was successful
Redirection 300–399 Further action needed
Client Error 400–499 Request error (client side)

18
Category Code Range Meaning
Server Error 500–599 Server failed to fulfill request

🔸 Common HTTP Status Codes


Code Meaning Example Use
200 OK Successful request Page loaded correctly
201 Created New resource created After POST request
204 No Content No data returned Successful delete
301 Moved Permanently Redirect Page moved to new URL
400 Bad Request Invalid request Missing parameters
401 Unauthorized Authentication required Login needed
403 Forbidden Access denied User not allowed
404 Not Found Resource missing Invalid URL
500 Internal Server Error Server crashed Bug in code

🔹 5. Example: HTTP Request–Response Flow (Browser + Server)


🔸 Scenario:
You fill out a login form and click Submit.
Browser sends (HTTP Request):
POST /login HTTP/1.1
Host: [Link]
Content-Type: application/x-www-form-urlencoded

username=john&password=1234
Server replies (HTTP Response):
HTTP/1.1 200 OK

19
Content-Type: text/html

<html>
<body>Welcome, John!</body>
</html>

🔹 6. HTTP Request & Response in JavaScript (AJAX / Fetch API)


📘 Using Fetch API (Modern JavaScript)
fetch('[Link] {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: [Link]({ name: 'Aarav', age: 20 })
})
.then(response => [Link]())
.then(data => [Link]('Response:', data))
.catch(error => [Link]('Error:', error));
Explanation:
 fetch() sends an HTTP Request.
 .then(response => [Link]()) handles the HTTP Response.
 Used for API communication without page reload.

🔹 7. Request and Response Headers


🔸 Common Request Headers

20
Header Purpose
Host Target server
User-Agent Info about browser
Accept Expected response type
Authorization Security token
Content-Type Type of data being sent

🔸 Common Response Headers


Header Purpose
Content-Type Type of returned data
Cache-Control Caching behavior
Set-Cookie Stores cookies
Server Web server info
Date Time response sent

🔹 8. HTTP vs HTTPS
Feature HTTP HTTPS
Security Unencrypted Encrypted with SSL/TLS
Port 80 443
Usage Basic communication Secure communication
Example [Link] [Link]

🔹 9. Summary
Concept Description
HTTP Request Message sent by client to server
HTTP Response Reply sent by server to client

21
Concept Description

Methods GET, POST, PUT, DELETE, etc.


Status Codes 200, 404, 500, etc.
Headers Additional request/response info
Body Data being sent or received
HTTPS Secure version of HTTP

🧩 Example Visualization
┌──────────────────────────────────────────────────────────────┐
│ CLIENT (Browser) │
│ ↓ Send HTTP Request → GET /home │
│ │
│ SERVER (Web Server) │
│ ↑ Send HTTP Response ← 200 OK + HTML Page │
└──────────────────────────────────────────────────────────────┘

✅ Short Quiz
1. What are the three main parts of an HTTP Request?
2. What is the purpose of HTTP status code 404?
3. Which HTTP method is used to delete a record?
4. What’s the difference between HTTP and HTTPS?
5. What does Content-Type header specify?

22

You might also like