Module 2
JavaScript Objects
JavaScript Objects:
In JavaScript, you can create your own custom objects using the ‘class’ keyword.
Example:
Imagine you want to create a blueprint for a car. This blueprint would tell you
what parts a car has (like brand, model, year). In JavaScript, this blueprint is
called a class.
Here's how you create a car object using a class:
1. Define the class:
class Car {
// This is where we define the car's parts (properties)
2. Add properties:
class Car {
constructor(brand, model, year) {
this.brand = brand; // Brand of the car
this.model = model; // Model of the car
this.year = year; // Year of manufacture
}
3. Create a car object:
let myCar = new Car("Toyota", "Camry", 2023);
This line creates a car object named myCar with the brand "Toyota",
model "Camry", and year 2023.
4. Use the object:
console.log(myCar.brand); // Output: Toyota
console.log(myCar.model); // Output: Camry
console.log(myCar.year); // Output: 2023
Native Objects:
Native Objects are those objects that are already built-in in JavaScript. This
means that you do not have to define or import them separately.
1. Array:
Meaning: A collection of items (elements) stored in a specific order.
Example:
let fruits = ["apple", "banana", "orange"];
console.log(fruits[0]); // Output: apple
console.log(fruits.length); // Output: 3
2. String:
Meaning: A sequence of characters (letters, numbers, symbols).
Example:
let message = "Hello, world!";
console.log(message.toUpperCase()); // Output: HELLO, WORLD!
console.log(message.length); // Output: 13
3. Date:
Meaning: Represents a specific point in time.
Example:
let today = new Date();
console.log(today.getFullYear()); // Output: Current year
console.log(today.getMonth() + 1); // Output: Current month (0-indexed)
console.log(today.getDate()); // Output: Current day
4. Math:
Meaning: Provides mathematical constants and functions.
Example:
console.log(Math.PI); // Output: 3.141592653589793
console.log(Math.sqrt(16)); // Output: 4
console.log(Math.max(10, 5, 20)); // Output: 20
5. Number:
Meaning: Represents numerical values.
Example:
let num = 10;
console.log(num.toString()); // Output: "10"
console.log(num.toFixed(2)); // Output: "10.00"
6. RegExp (Regular Expression):
A RegExp is a pattern used to search and match text.
Example
Let's say we have a text: "This is a sample text."
We want to find all occurrences of the word "is" in this text.
RegExp Pattern
We create a RegExp pattern: /is/g
Here's what each part means:
- /: Starts the RegExp pattern
- is: The text we're searching for (literally "is")
- /: Ends the RegExp pattern
- g: Flag that means "global" search (find all occurrences, not just the first
one)
Matching the Pattern
We use the match() method to search for the pattern in the text:
let text = "This is a sample text.";
let pattern = /is/g;
console.log(text.match(pattern)); // Output: ["is", "is"]
Output
The output is an array of all matches found in the text. In this case, we
found two occurrences of the word "is".
7. Cookies:
Cookies are small text files that are stored by a website in a user's
browser. These files help a website store information about the user, such
as the user's name, password, or preferences.
In JavaScript, you use the document.cookie property to access cookies.
Some important concepts of Cookie:
1. Cookie Name: The name of the cookie that is set by the website.
2. Cookie Value: The value of the cookie that is set by the website.
3. Expiration Date: The expiration date of the cookie that is set by the
website.
4. Path: The path of the cookie that is set by the website.
Some examples of working with cookies in JavaScript:
1. Setting a Cookie:
document.cookie = "username=John Doe; expires=Fri, 31 Dec 2022
23:59:59 GMT";
2. Getting Cookie:
var cookieValue = document.cookie.match(/username=([^;]*)/)[1];
console.log(cookieValue); // Output: John Doe
3. To delete the cookie:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00
GMT";
Event and Event Handlers:
Event: Events are actions performed by the user or the browser, such as clicking
a button, submitting a form, or loading a webpage.
Event Handlers: Event Handlers are functions that are run in response to events.
These functions can provide information about events and perform specific
actions.
HTML Events:
HTML Events are actions performed by the user or browser, such as clicking a
button, submitting a form, or loading a webpage. These events are associated
with HTML elements and are defined as their attributes.
Example:
<button onclick="alert('Button clicked!')">Click me!</button>
In this example, onclick is an HTML event that is triggered when the button is
clicked.
DOM Events:
DOM Events are actions performed on elements of the Document Object Model
(DOM). These events are associated with HTML elements, but they are handled
by JavaScript.
Example:
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
alert('Button clicked!');
});
In this example, click is a DOM event that is triggered when the button is
clicked.
DOM Event Listener:
DOM Event Listener is a JavaScript function that listens to DOM events and
performs actions in response to them. These listeners are associated with DOM
elements and provide information about these events.
Example:
const button = document.getElementById('myButton');
button.addEventListener('click', function(event) {
alert('Button clicked!');
console.log(event.target); // Button element
});
In this example, addEventListener is a method that sets the DOM event listener.
The event object contains information about the event, such as the event target
(button element).
1. onAbort: Event that triggers the tab when the user stops loading an image
or video.
Example: <img src="image.jpg" onabort="alert('Image loading
aborted!')">
2. onBlur: Event that triggers the tab when the user removes focus from a
form field or element.
Example: <input type="text" onblur="alert('Field blurred!')">
3. onChange: Event that triggers the tab when the user modifies a form field
or element.
Example: <input type="text" onchange="alert('Field changed!')">
4. onClick: Event that triggers the tab when the user clicks an element.
Example: <button onclick="alert('Button clicked!')">Click me!</button>
5. onDblClick: Event that triggers the tab when the user double-clicks an
element.
Example: <button ondblclick="alert('Button double-clicked!')">Double-
click me!</button>
6. onError: Event that triggers the tab when an error occurs, such as an error
in loading an image or script.
Example: <img src="image.jpg" onerror="alert('Error loading image!')">
7. onFocus: Event that triggers the tab when the user focuses on a form field
or element.
Example: <input type="text" onfocus="alert('Field focused!')">
8. onKeyDown: Event which tab is triggered when the user presses a
keyboard key.
Example: <input type="text" onkeydown="alert('Key pressed!')">
9. onKeyPress: Event which tab is triggered when the user presses a
keyboard key and a character is entered.
Example: <input type="text" onkeypress="alert('Character entered!')">
10. onKeyUp: Event which tab is triggered when the user releases a keyboard
key.
Example: <input type="text" onkeyup="alert('Key released!')">
11. onLoad: Event that triggers when a webpage or image is loaded.
Example: <body onload="alert('Page loaded!')">
12. onMouseDown: Event that is triggered when the user presses a mouse
button.
Example: <button onmousedown="alert('Mouse button pressed!')">Click
me!</button>
13. onMouseMove: Event that is triggered when the user moves a mouse.
Example: <div onmousemove="alert('Mouse moved!')">Move me!</div>
14. onMouseOut: Event which tab is triggered when the user moves the
mouse away from an element.
Example: <button onmouseout="alert('Mouse out!')">Click me!</button>
15. onMouseOver: Event which tab is triggered when the user moves the
mouse over an element.
Example: <button onmouseover="alert('Mouse over!')">Click
me!</button>
16. onMouseUp: Event which tab is triggered when the user releases a
mouse button.
Example: <button onmouseup="alert('Mouse button released!')">Click
me!</button>
17. onReset: Event which tab is triggered when user resets a form.
Example: <form onreset="alert('Form reset!')">
18. onResize: Event which tab is triggered when user resizes a window.
Example: <body onresize="alert('Window resized!')">
19. onSelect: Event which tab is triggered when user selects a text.
Example: <input type="text" onselect="alert('Text selected!')">
20. onSubmit: Event which tab is triggered when user submits a form.
Example: <form onsubmit="alert('Form submitted!')">
21. onload: when the document is unloaded.
Example: <body onload="alert('Document unloaded!')">