WT _Unit-03
WT _Unit-03
WT _Unit-03
History:
2. Documentation
Learning
Resources:
3. JavaScript
Forms Form
Handling:
<form id="myForm">
</form>
<script>
document.getElementById("myForm").onsubmit = function(event) {
if (!name) {
};
</script>
4. Statements
Types of Statements:
} else {
Functions
function greet(name) {
Return value
By default, if a function's execution doesn't end at a return statement, or if the
return keyword doesn't have an expression after it, then the return value
is undefined. The return statement allows you to return an arbitrary value from the
function. One function call can only return one value, but you can simulate the
effect of returning multiple values by returning an object or array
and destructuring the result.
Passing arguments
Parameters and arguments have slightly different meanings, but in MDN web docs,
we often use them interchangeably. For a quick reference:
function formatNumber(num) {
return num.toFixed(2);
formatNumber(2);
In this example, the num variable is called the function's parameter: it's declared in
the parenthesis-enclosed list of the function's definition. The function expects the
num parameter to be a number — although this is not enforceable in JavaScript
without writing runtime validation code. In the formatNumber(2) call, the number
2 is the function's argument: it's the value that is actually passed to the function in
the function call. The argument value can be accessed inside the function body
through the corresponding parameter name or
the arguments object.
Arguments are always passed by value and never passed by reference. This means
that if a function reassigns a parameter, the value won't change outside the
function. More precisely, object arguments are passed by sharing, which means if
the object's properties are mutated, the change will impact the outside of the
function. For example:
function updateBrand(obj) {
obj = null;
}const car = {
brand: "Honda",
model:
"Accord", year:
1998,
};
console.log(car.brand); // Honda
updateBrand(car);
console.log(car.brand); // Toyota
The this keyword refers to the object that the function is accessed on — it does
not refer to the currently executing function, so you must refer to the function
value by name, even within the function body.
Defining functions
function myFunction() {
// code to be executed
2. Function Expressions:
const myFunction = function() {
// code to be executed
}
// code to be executed
};
Or
const greet = (name) => `Hello,
${name}!`;
console.log(greet("Bob")); // Output:
Hello, Bob!
4. Anonymous Functions: These are functions without a name and can be used in
function expressions:
};
(function() {
// code to be executed
})();
function higherOrderFunction(callback)
{ callback();
function* generatorFunction() {
yield 'value';}
someAsyncCall();
}
Each type of function serves different purposes and can be used based on the
requirements of your code.
6. Objects
What are Objects?
The Object type represents one of JavaScript's data types. It is used to store various
keyed collections and more complex entities. Objects can be created using the
Object() constructor or the object initializer / literal syntax.
Creating Objects:
const person = {
name: "John",
age: 30,
greet: function() {
console.log("Hello, " +
this.name);
}
};
The Object type represents one of JavaScript's data types. It is used to store various
keyed collections and more complex entities. Objects can be created using the
Object() constructor or the object initializer / literal syntax.
Description
Nearly all objects in JavaScript are instances of Object; a typical object inherits
properties (including methods) from Object.prototype, although these propertiesmay
be shadowed (a.k.a. overridden). The only objects that don't inherit
from Object.prototype are those with null prototype, or descended from other
null prototype objects.
Changes to the Object.prototype object are seen by all objects through prototype
chaining, unless the properties and methods subject to those changes are overridden
further along the prototype chain. This provides a very powerful although
potentially dangerous mechanism to override or extend object behavior. To make it
more secure, Object.prototype is the only object in the core JavaScript language that
has immutable prototype — the prototype of Object.prototype is always null and
not changeable.
You should avoid calling any Object.prototype method directly from the instance,
especially those that are not intended to be polymorphic (i.e. only its initial behavior
makes sense and no descending object could override it in a meaningful way). All
objects descending from Object.prototype may define a custom own property that
has the same name, but with entirely different semantics from what you expect.
Furthermore, these properties are not inherited by null-prototype objects. All
modern JavaScript utilities for working with objects are static. More specifically:
In case where a semantically equivalent static method doesn't exist, or if you really
want to use the Object.prototype method, you should
directly call() the Object.prototype method on your target object instead, to prevent
the object from having an overriding property that produces unexpectedresults.
const obj =
{ foo: 1,
// You should not define such a method on your own object,
// but you may not be able to prevent it from happening if
// you are receiving the object from external input
propertyIsEnumerable() {
return false;
},
};
There isn't any method in an Object itself to delete its own properties (suchas
Map.prototype.delete()). To do so, one must use the delete operator.
null-prototype objects
An object with a null prototype can behave in unexpected ways, because it doesn't
inherit any object methods from Object.prototype. This is especially true when
debugging, since common object-property converting/detecting utility functions
may generate errors, or lose information (especially if using silent error-traps that
ignore errors).
We can add the toString method back to the null-prototype object by assigning it
one:
nullProtoObj.toString = Object.prototype.toString;
// since new object lacks toString, add the original generic one back
console.log(nullProtoObj.toString());
// shows "[object Object]"
console.log(`nullProtoObj is:
${nullProtoObj}`);
// shows "nullProtoObj is: [object Object]"
In practice, objects with null prototype are usually used as a cheap substitute
for maps. The presence of Object.prototype properties will cause some bugs:
function getAge(name)
{ return ages[name];
}
hasPerson("hasOwnProperty"); // true
getAge("toString"); // [Function: toString]
Using a null-prototype object removes this hazard without introducing too much
complexity to the hasPerson and getAge functions:
In such case, the addition of any method should be done cautiously, as they can be
confused with the other key-value pairs stored as data.
Making your object not inherit from Object.prototype also prevents prototype
pollution attacks. If a malicious script adds a property to Object.prototype, it will be
accessible on every object in your program, except objects that have null
prototype.
JavaScript also has built-in APIs that produce null-prototype objects, especially
those that use objects as ad hoc key-value collections. For example:
Object coercion
Many built-in operations that expect objects first coerce their arguments to objects.
The operation can be summarized as follows:
There are two ways to achieve nearly the same effect in JavaScript.
Unlike conversion to primitives, the object coercion process itself is not observable
in any way, since it doesn't invoke custom code
like toString or valueOf methods.
Constructor
Object()
Static methods
Object.assign()
Copies the values of all enumerable own properties from one or more source
objects to a target object.
Object.create()
Creates a new object with the specified prototype object and properties.
Object.defineProperties()
Object.defineProperty()
Object.entries()
Object.freeze()
Object.fromEntries()
Returns a new object from an iterable of [key, value] pairs. (This is the reverse
of Object.entries).
Object.getOwnPropertyDescriptor()
Returns a property descriptor for a named property on an object.
Object.getOwnPropertyDescriptors()
Object.getOwnPropertyNames()
Object.getOwnPropertySymbols()
Returns an array of all symbol properties found directly upon a given object.
Object.getPrototypeOf()
Object.groupBy()
Object.hasOwn()
Object.is()
Compares if two values are the same value. Equates all NaN values (which
differs from both IsLooselyEqual used by == and IsStrictlyEqual used
by ===).
Object.isExtensible()
Object.isFrozen()
Object.isSealed()
Object.keys()
Object.preventExtensions()
Object.seal()
Object.setPrototypeOf()
Object.values()
Instance properties
Points to the object which was used as prototype when the object was
instantiated.
Object.prototype.constructor
Instance methods
Object.prototype. defineGetter () Deprecated
Associates a function with a property that, when set, executes that function
which modifies the property.
Object.prototype.hasOwnProperty()
Object.prototype.isPrototypeOf()
Returns a boolean indicating whether the object this method is called uponis
in the prototype chain of the specified object.
Object.prototype.propertyIsEnumerable()
Object.prototype.toLocaleString()
Calls toString().
Object.prototype.toString()
Object.prototype.valueOf()
Examples
The following example creates empty objects using the new keyword with
different arguments:
You can use the Object() constructor to create an object wrapper of a primitive
value.
Object prototypes
When modifying prototypes with hooks, pass this and the arguments (the call state)
to the current behavior by calling apply() on the function. This pattern can be used
for any prototype, such as Node.prototype, Function.prototype, etc.
Ajax can be used to create single-page apps, in which the entire web app consists
of a single document, which uses Ajax to update its content as needed.
This technique is so common in modern web development that the specific term
"Ajax" is rarely used.
• Uses the XMLHttpRequest object or the Fetch API to send requests to the
server and handle responses.
fetch("https://api.example.com/data")
Types of IP Addresses
1. IPv4: Uses a 32-bit address scheme allowing for over 4 billion unique
addresses. An example IPv4 address is 192.168.1.1.
2. IPv6: Uses a 128-bit address scheme to accommodate the growing number of
devices. An example IPv6 address is
2001:0db8:85a3:0000:0000:8a2e:0370:7334.
Subnetting
Subnetting divides a larger network into smaller sub-networks, improving
performance and security. Each subnet has its own range of IP addresses.
IP Address Allocation
The Internet Assigned Numbers Authority (IANA) and regional Internet registries
manage the allocation of IP addresses to ensure they are unique and properly
distributed.
FACTORY METHODS
Factory methods in networking and web technology are often used to create
instances of network-related classes in a way that promotes flexibility and loose
coupling. Here's a detailed look at how factory methods work in this context:
The Factory Method Design Pattern is a creational pattern that provides an interface
for creating objects in a superclass but allows subclasses to alter the type of objects
that will be created. This pattern is particularly useful when a class cannot anticipate
the class of objects it needs to create.
In Java, factory methods are commonly used in the java.net package to create
instances of network-related classes. Here are some examples:
Conclusion
Factory methods are a powerful tool in networking and web technology, providing a
way to create objects in a flexible and loosely coupled manner. They help in
managing complexity and promoting code reusability.
INSTANCE METHODS
Instance methods are functions defined in a class that operate on instances (objects)
of that class. In networking and web technology, these methods are crucial for
performing various operations and managing network communication. Here's a
detailed look at instance methods in this context:
• Access: Instance methods have access to the instance variables (self in Python,
this in Java) and other instance methods within the same class.
• Reuse and Maintenance: They can be reused by different objects, making the
code more maintainable and scalable.
• Sending and Receiving Data: Instance methods manage the process of sending
and receiving data over a network.
TCP/IP client sockets are fundamental in networking and web technology, enabling
communication between client and server applications. Here’s a detailed overview:
1. Introduction to Sockets
a. Socket Creation
2. Address and Port: Specify the server address and port number to connect to.
c. Sending Data
1. Send Method: Use the send() or equivalent method to transmit data to the
server
d. Receiving Data
1. Receive Method: Use the recv() or equivalent method to receive data from the
server.
1. Close Method: Close the socket connection using the close() method.
4. Example Code
import java.io.*;
import java.net.*;
"Hello, server!";
Structure of a URL
scheme://user:password@host:port/path?query#fragment
1. Scheme: Specifies the protocol used to access the resource (e.g., http, https,
ftp).
o Example: https://
2. User Info (optional): Username and password for accessing the resource. This
component is less common and often not included due to security concerns.
o Example: user:password@
3. Host: The domain name or IP address of the server where the resource is
located.
o Example: www.example.com
4. Port (optional): The network port on the host to connect to. If omitted, the
default port for the scheme is used (e.g., 80 for HTTP, 443 for HTTPS).
o Example: :8080
https://user:[email protected]:8080/path/to/resource?search=keyw
ord#section
Scheme
User Info
• Not commonly used due to security reasons, but it includes credentials for
accessing resources.
• Example: ftp://username:[email protected]
Host
• Can be a domain name (e.g., www.example.com) or an IP address (e.g.,
192.0.2.1).
• The host component is essential for locating the server where the resource
resides.
Port
• Indicates the port number on the server to connect to.
• Default ports are typically implied: 80 for HTTP, 443 for HTTPS, and 21 for
FTP.
Path
Query
• Contains key-value pairs separated by &, used for passing parameters to the
server.
• Example: ?id=123&name=John
Fragment
URL Encoding
Understanding URLs is crucial for navigating the web, developing web applications,
and configuring network services. URLs are the backbone of how we access and
share resources on the internet.
URL Composition
A URL connection in networking and web technology is typically managed through
a class or library that allows you to connect to a URL and perform various operations
such as sending requests and receiving responses. Let's delve into the details, using
Java as an example for illustration since it has a robust URLConnection class.
1. What is URLConnection?
2. Open a Connection
o Definition: The openConnection() method of the URL class returns a
URLConnection object that represents a connection to the remote object
referred to by the URL.
o Example:
Java
Here's a complete example that demonstrates how to read content from a URL using
URLConnection:
java
import java.io.*;
import java.net.*;
• Flexibility: Supports various protocols (HTTP, HTTPS, FTP, etc.) and allows
customization through request properties.
• Integration: Easily integrates with other Java I/O streams for reading and
writing data.
Understanding URL connections is crucial for tasks like web scraping, accessing
web services, and automating web interactions.
TCP/IP Server Sockets
1. Define the Server Address and Port: Choose an IP address and port
number for the server to listen on.
2. Create the Server Socket: Use a socket library to create a server
socket.
1. Bind the Socket to the Address and Port: Associate the server socket
with the IP address and port number.
3. Example in Java
import java.io.*;
import java.net.*;
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received: " + inputLine);
out.println("Echo: " + inputLine);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
4. Key Points of TCP/IP Server Sockets
5. Use Cases
6. Advanced Features
1. What is a Datagram?
• Characteristics:
3. Datagram Structure
a. Header
b. Data
• Payload: The actual data being transmitted. The size of the payload
can vary depending on the application and the network's maximum
transmission unit (MTU).
4. Example Code
The server listens for incoming datagrams and prints the received data.
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
// Message to be sent
String message = "Hello, Datagram Server!";
byte[] sendBuffer = message.getBytes();
1. DatagramServer.java:
2. DatagramClient.java: