Sie sind auf Seite 1von 28

INTERNET:

Internet: the network of networks connected via the public backbone and communicating using TCP/IP
communication protocol
Global Communication Network
Commercial Internet dial-up access offered
Economic
Increase network usage
Reduced unit cost
Backbone initially supplied by NSFNET, privately funded (ISP fees) beginning in 1995
Private telecommunication firms
TCP/IP:
TCP/IP Single Protocol
TCP/IP actually two different protocols.
TCP-transport Layer IP-Network layer
Treated as one some bulk of services are built on the top of both the TCP and IP protocols
-> e-mail, Web browsing, File downloads, accessing remote databases
INTERNET PROTOCOL:

IP is the fundamental protocol defining the Internet (as the name implies!)

Internet protocols developed as part of ARPANET research


ARPANET began using TCP/IP in 1982
Designed for use both within local area networks (LANs) and between networks
IP address:
32-bit number (in IPv4)
Each device on the internet has one or more IP addresses
Written as four dot-separated bytes, e.g. 192.0.34.166
Each decimal number represents one byte of the IP address
IP function: transfer data from source device to destination device
IP source software creates a packet representing the data
Header: source and destination IP addresses, length of data, etc.
Data itself
If destination is on another LAN, packet is sent to a gateway that connects to more than one

network
Gateway is a device that is connected to the source computers network as well as to at least one

other network.

The sequence of computers that a packet travels through from source to destination is known as

its route.
How does the computer choose the next computer in the route for a packet?
A separate protocol BGP-4 is used to pass network connectivity information between

gateways so that each computer can choose a good next hop for each packet it receives.
IP software adds error detection information ( a checksum) to each packet
Limitations of IP:
No guarantee of packet delivery (packets can be dropped)
Unreliable
Communication is one-way (source to destination)

TRANSMISSION CONTROL PROTOCOL (TCP):

TCP is a higher-level protocol extends IP to provide additional functionality


Reliable communication based on the concept of communication
TCP adds concept of a connection on top of IP
Provides guarantee that packets delivered
Provide two-way (full duplex) communication
A and B both send messages to one another at the same time.
Reliable data transmission by demanding an ACK for each packet it sends via IP
Splitting longer messages into shorter ones
Reassembling on receiver side.

TCP also adds concept of a port


The port concept allows TCP to communicate with many different applications on a

machine.
TCP header contains port number representing an application program on the destination
computer
Some port numbers have standard meanings
Example: port 25 is normally used for email transmitted using the Simple Mail
Transfer Protocol (SMTP)
Other port numbers are available first-come-first served to any application
Assigned by IANA(Internet Assigned numbers Authority)
0-1023 requested only by the applications that are run by the system at boot-up
1024-65535 used by the first application on a system

USER DATAGRAM PROTOCOL (UDP):


Like TCP in that:
Builds on IP
Provides port concept
Unlike TCP in that:
No connection concept
No transmission guarantee
No two way connection
Advantage of UDP vs. TCP:
Lightweight, so faster for one-time messages
less complexity in order to reduce overhead
HIGHER-LEVEL PROTOCOLS:

IP ~ the telephone network


TCP ~ calling someone who answers, having a conversation, and hanging up
UDP ~ calling someone and leaving a message
DNS ~ directory assistance (names with numbers)

Many protocols build on TCP


Telephone analogy: TCP specifies how we initiate and terminate the phone call, but some
other protocol specifies how we carry on the actual conversation

Some examples:
SMTP (email)
FTP (file transfer)
HTTP (transfer of Web documents)
Primary TCP-based protocol used for communication between web servers and
browsers called HTTP
IP is key component in the definition of Internet
HTTP - WWW

1.3 World Wide Web

Unique feature of Web: support for hypertext (text containing links)


Communication via Hypertext Transport Protocol (HTTP)
Document representation using Hypertext Markup Language (HTML)
The Web is the collection of machines (Web servers) on the Internet that provide

information, particularly HTML documents, via HTTP.


Machines that access information on the Web are known as Web clients. The web

client(Web browser) is software used by an end user to access the Web.


Machines provide information to the Web are known as Web servers.

Hypertext Transport Protocol (HTTP):


HTTP is based on the request-response communication model:
Client sends a request
Server sends a response
Is a Communication Protocol
HTTP is based on the request-response communication model:
Client sends a request
Server sends a response
Format of the message is dictated by HTTP
HTTP send the message using TCP
HTTP is a stateless protocol:
The protocol does not require the server to remember anything about the client requests.
Each request is executed independently, without any knowledge of the requests that came

before it
Normally implemented over a TCP connection (80 is standard port number for HTTP)
Typical browser-server interaction:
User enters Web address in browser
Browser uses DNS to locate IP address
Browser opens TCP connection to server
Browser sends HTTP request over connection
Server sends HTTP response to browser over connection
Browser displays body of response in the client area of the browser window

HTTP Request Header


Connect to 67.228.171.112 on port 80 ... ok
GET / HTTP/1.0[CRLF]
Host: www.stjosephs.ac.in[CRLF]
Connection: close[CRLF]
User-Agent: Web-sniffer/1.0.46 (+http://web-sniffer.net/) [CRLF]
Accept-Encoding: gzip[CRLF]
Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7[CRLF]
Cache-Control: no-cache[CRLF]
Accept-Language: de,en;q=0.7,en-us;q=0.3[CRLF]
Referer: http://web-sniffer.net/ [CRLF]
[CRLF]

HTTP Response Header


Name

Value

Delim

Status: HTTP/1.1 200 OK


Date:
Tue, 17 Dec 2013 04:23:26 GMT
Server:
Apache/2.2.24 (Unix) mod_ssl/2.2.24 OpenSSL/1.0.0-fips
Last-Modified:
ETag:
Accept-Ranges:
Content-Length:
Connection:
Content-Type:

mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635


Sat, 30 Nov 2013 09:20:55 GMT
"1f02cce-4644-4ec6176bf4b9f"
bytes
17988
close
text/html

HTTP REQUEST
Connect to 67.228.171.112 on port 80 ... ok
GET / HTTP/1.0[CRLF] ----------------start line
Host: www.stjosephs.ac.in[CRLF]
request uri

HEADER FIELDS

Connection: close[CRLF]
User-Agent: Web-sniffer/1.0.46 (+http://web-sniffer.net/) [CRLF]
Accept-Encoding: gzip[CRLF]
Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7[CRLF]
Cache-Control: no-cache[CRLF]
Accept-Language: de,en;q=0.7,en-us;q=0.3[CRLF]
Referer: http://web-sniffer.net/ [CRLF]

Each request message begins with a request line (START LINE), which contains three critical
pieces of information: After the start line come a set of message headers related to the request, followed
by a blank line and then optionally, the message body of the request as shown below
Structure of Request:
start line
header field(s)
blank line
optional body

Start line

A start line (which contains the method the client is requesting; the URI of the resource
upon which the client wishes the action to be performed and the version of HTTP that the client
is using).
Example: GET / HTTP/1.1
Three space-separated parts:
HTTP request method
Request-URI
HTTP version
Request methods:
HEAD

Used to ask only for information about a document, not for the
document itself. It's often used by clients who use caching, to see

GET
POST
PUT
DELETE
TRACE

if the document has changed since it was last accessed.


Requests a representation of the specified resource.
Submits data to be processed to the identified resource.
Uploads a representation of the specified resource.
Deletes the specified resource.
Echoes back the received request, so that a client can see what (if
any) changes or additions have been made by intermediate

OPTIONS

servers.
Returns the HTTP methods that the server supports for specified
URL

Request URI:
URIs are of two types:
Uniform Resource Name (URN)
Can be used to identify resources with unique names, such as books (which have

unique ISBNs)
Uniform Resource Locator (URL)
Specifies location at which a resource can be found
In addition to http, some other URL schemes are https, ftp, mailto, and file

Header field structure:


After the request line come any of the headers that the client wants to include in the message; it is
in these headers that details are provided to the server about the request. The headers all use the
same structure as
field name : field value
Syntax
Field name is not a case sensitive
Field values may contain MIME types (Multipurpose Internet Mail Extensions),
quality values. MIME is a convention for specifying content type of a message.

MIME Type
text/plain

Some common content types:,


Description
Plain text. Default if data is primarily text

text/html

and no other type detected.


HTML. Default if common tags detected

image/gif
image/jpeg
application/octet-

and server does not supply image/* type.


Graphics Interchange Format (GIF).
JPEG image.
Binary file. Default if data is primarily

stream

binary.

HTTP RESPONSE :
After receiving and interpreting a request message, a server responds with an HTTP response message.
Name

Value

Status: HTTP/1.1 200 OK


Date:

Tue, 17 Dec 2013 04:23:26 GMT

Server:

Apache/2.2.24 (Unix) mod_ssl/2.2.24 OpenSSL/1.0.0-fips

Last-Modified:

mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635


Sat, 30 Nov 2013 09:20:55 GMT

ETag:

"1f02cce-4644-4ec6176bf4b9f"

Accept-Ranges:

bytes

Content-Length:

17988

Connection:

close

Content-Type:

text/html

Structure of the response:


status line
header field(s)
blank line
optional body

Status line: The first line of a Response message is the Status-Line, consisting of the protocol
version followed by a numeric status code and its associated textual phrase.
Example: HTTP/1.1 200 OK
It has three space-separated parts:
HTTP version
status code
reason phrase in text (intended for human use)
Status code: to display the status of the response message
is a three-digit number
Classified into five classes. First digit is class of the status code:
1xx:

Request received, continuing process

Informational
2xx: Success

The action was successfully received, understood,

3xx: Redirection

and accepted
Further action must be taken in order to complete the

4xx: Client Error

request
The request contains bad syntax or cannot be

5xx:

fulfilled
The server failed to fulfill an apparently valid request

Server

Error
Some common status codes:
200: OK.
302: This code indicates that a page has been temporarily redirected to another
URL. This means that the page is still active, just temporarily moved to another
URL.
403: Some of you may have come across this, also known as the Forbidden
Request. Basically it means that you have made a legal request, but the server is
refusing to respond to it.
404: The most common of the Broken Site Errors! Basically this is where the URL
no longer exists or cannot be found, so you will be redirected to a broken holding
page.
500: Just a generic Server error message, this comes up when there is nothing else
to explain a problem.
501: This is where the Server you a requesting information from does not
understand the method in which you are requesting the information, or there is not
a fulfilled request.
502: Simply an invalid response was received by the server, from the request that
you have made.

Common header fields:


Accept-Ranges
Date
Last-Modified
Expires

What partial content range types this server supports


The date and time that the message was sent
The last modified date for the requested object
Gives the date/time after which the response is considered

ETag
Location

old
A hash code of the resource returned
Used in redirection, or when a new resource has been
created

Server

A name for the server

Links:
Hyperlinks are produced by the anchor element <a>
Clicking on a hyperlink causes browser to issue GET request to URL specified in href attribute
and render response in client area
<a href="http://www.motive.co.nz">Motive</a>
<a> element called anchor. Link has two ends : anchors and direction
Anchors can be used as source (previous example) or destination
Source anchors
A source anchor is created in an HTML document (webpage) by adding an anchor
element (<a>) with a hypertext reference (href) containing a uniform resource identifier (URI).
Eg:<a href="http://www.motive.co.nz">Motive</a>
Destination anchors
To link to a point within a webpage, for example to link to content below the first fold, a
destination anchor must be added.
A destination anchor is created by adding a fragment identifier, this is either:
An anchor element, with a name attribute, or
Any other element, with an id attribute.
Eg:
<html>
<A href="#section1">Introduction</A><BR>
<A href="#section2">Some background</A><BR>
<A href="#section2.1">On a more personal note</A><BR>
..
<H2 id="section1">Introduction</H2>
...section 1...
<H2 id="section2">Some background</H2>
...section 2...
<H3 id="section2.1">On a more personal note</H3>
...section 2.1...
</html>
ABSOLUTE URL AND RELATIVE URL
Absolute URL
An Absolute URL is, thus, something that is independent or free from any relationship. When you
use an absolute URL, you point directly to a file. Hence, an absolute URL specifies theexact location of a
file/directory on the internet. It also follows that each absolute URL is unique
Eg: http://www.webdevelopersnotes.com/images/email.gif
specifies an image file email.giflocated in the images directory, under
www.webdevelopersnotes.com domain name.
Relative URL
A relative URL points to a file/directory in relation to the present file/directory

Using an Absolute URL in an <img> tag


<img src="http://www.webdevelopersnotes.com/images/email.gif" width="..." height="..." />
Using a Relative URL in an <IMG> tag
<img src="../images/email.gif" width="..." height="..." />.
We, thus, instruct the browser to first go one level up (i.e. to the document root) and then move
to the images directory and pick up the file email.gif.
The two peroids (..) instruct the server to move up one directory (which is the root directory)
Adv:
It is easy to transfer a web site from one domain name to another.
Also, relative URLs would be shorter than absolute URLs and hence the file size of the web page
would reduce .

XHTML DTD:
XML is used to define the syntax of XHTML
Set of XML files that define a language are known as the document type definition (DTD)
DTD primarily consists of declarations:
Element type: name and content of elements
Attribute list: attributes of an element
Entity: define meaning of, e.g., &gt;
Eg:
<!ELEMENT html (head, body)>
<!ATTLIST html
lang
NMTOKEN
xml:lang
NMTOKEN
dir
(ltr|rtl)
id
ID
xmlns
CDATA
<!ENTITY gt &#62;>

#IMPLIED
#IMPLIED
#IMPLIED
#IMPLIED
#FIXED 'http://www.w3.org/1999/xhtml' >

1) Element type:
Used to specify the set of all valid elements in the language defined by DTD
Eg: <!ELEMENT element-name (element-content)(iterators)>
Content Specification:

Eg:
<!ELEMENT html (head, body)>
<!ELEMENT br EMPTY>

-> Sequence
-> Empty

Eg:
<!ELEMENT select (option|optgroup)*>
2) Attribute List Declaration:

Provides information about the valid attributes for an element

Eg: <!ATTLIST html


lang
xml:lang
dir
id
xmlns

NMTOKEN
NMTOKEN
(ltr|rtl)
ID
CDATA

#IMPLIED
#IMPLIED
#IMPLIED
#IMPLIED
#FIXED 'http://www.w3.org/1999/xhtml' >

Eg 1:
<!ATTLIST person number CDATA #REQUIRED>
Valid XML:
<person number="5677" />
Invalid XML:
<person />
Eg 2:
<!ATTLIST sender company CDATA #FIXED "Microsoft">
Valid XML:
<sender company="Microsoft" />
Invalid XML:
<sender company="W3Schools" />

3) ENTITY DECLARATION:

Entity declaration is essentially a macro


Two types of entity:
General: referenced from HTML document using &
<!ENTITY gt &#62;>
Parameter: reference from DTD using %

<!ENTITY %lang

NMTOKEN>

Eg:
<p> if a&gt;b </p>-> Prints a>b

UNIT-2
SELECTOR STRING:

Consist of two parts


Selector string-Indicates the elements to which the rule should apply
Declaration block in { }-Specifies a value for one style property of those elements
List of declaration separated by semicolons
It is syntactically legal to split rules over several lines or write multiple rules on a single line
Parts of a style rule (or statement)

Selector Strings
Type selector :Each of the selector simply the name of an element type
h1,h2,h3,h4,h5,h6 { background-color : purple }
Universal selector : Every possible element type
* { font-weight : bold }
ID selector :
#p1, #p3 { background-color : aqua }
<p id="P1" class="takeNote">
Paragraph with id="P1" and class="takeNote".
</p>
.
.
.
<p id="p3">
This paragraph (id="p3") contains a
<a href="http://www.example.net">hyperlink</a>.
Class selector :
#p1, .takeNote { font-style : italic }
span.special { font-size : x-large }
The difference between an ID and a class is that an ID can be used to identify one
element, whereas a class can be used to identify more than one.
Descendant selector : used to select elements that are descendants of another element in the
document tree.
ul span { font-variant : small-caps }
ul ol li { letter-spacing : lem }

Predefined pseudo classes associated with anchor element


a:link { color : black } link that has not been visited recently
a:visited { color : yellow } visited once next time loaded
a:hover { color : green } positioning cursor over link without clicking the mouse button
cause link to change green
a:active { color : red } - clicking and holding the mouse button change the colour to red

DIFFERENT TYPES OF STYLESHEETS:

1. To create an inline style


a. Add the style attribute to the HTML tag.
b. The style declaration must be enclosed within double quotation marks.
2. To create an embedded style
a. Insert a <style> tag within the head section of HTML file.
b. Within the <style> tag, enclose the style declarations need to the entire Web page.
c. The style sheet language identifies the type of style used in the document.
d. The default and the most common language is text/css for use with CSS.
3. To create an External styles
a. Create a text file containing style declarations
b. Create a link to that file in each page of the Web site using a <link> tag.
c. Specify the link attributes, such as href, rel, and type.
d. Link a style sheet, the value of the href attribute should be the URL of the
linked document, the value of the rel attribute should be stylesheet and the
value of the type attribute should be text/css.
4. Write the source code for the separate style sheet and finally terminate the program.
Definitions:
Inline styles are added to each tag within an HTML file using Style attribute.
Embedded styles are applied to an entire HTML file using Style element.
External style sheets are placed in an external file and linked with pages in the Web site.
PROGRAM:
EXTERNAL.CSS
body{background-color:green;}
p{color:blue;}
h3{color:white;}
ul.a {list-style-type: square;}<!--Desendent Selector Element ul followed by class (.a)-->
ul.b {list-style-type: circle;}
ol.c{list-style-type:upper-roman;}
ol.d{list-style-type:lower-alpha;}
#hi{text-color:white;}<!--Id Selector-->
body{background-image:url('tamilnadu.jpg');}
h1{text-align:center;}<!--Type Selector-->
p.date{text-align:right;}<!--Desendent Selector-->
EXTERNAL.HTML
<html>

<head>
<link rel="stylesheet" type="text/css" href="ext.css"/><!-- Links External Style Sheet ext.css-->
</head>
<body>
<h1>EXTERNAL STYLE SHEET</h1>
<h3>a white header</h3>
<ul class="b">
<li>liststyletype-circle</li>
<li>liststyletype-circle</li>
<li>liststyletype-circle</li>
</ul>
<ol class="c">
<li>upper-roman</li>
<li>upper-roman</li>
</ol>
<ol class="d">
<li>lower_alpha</li>
<li>lower_alpha</li>
</ol>
<p class="date">
This paragraph has a blue font .the back ground colour is green because of external style sheet</p>
</body>
</html>

INTERNAL.HTML
<html>
<head>
<style>
body{background-color:grey;}
p{color:white;}
ul.a {list-style-type: circle;}
ul.b {list-style-type: square;}
#p1{font-family:"Times New Roman",Times,serif;}
</style>
</head>
<body><!--Type Selector-->
<center>
<h2>INTERNAL STYLE SHEET</h2>
</center>
<ul class="b"><!--Desendent Selector Element ul followed by class (.b)-->
<li>liststyletype:square</li>
<li>liststyletype:square</li>
</ul>
<p id="p1">This page USES internal css using style tag</p><!-- ID Selector-->
</body>
</html>
INLINE.HTML
<html>
<head>
<title>inline css</title>
</head>
<BODY style="background-color:red";><!-- INLINE Stylesheet style keyword as an attribute-->
<center>
<h2>INLINE STYLE SHEET</h2>
</center>
<p style="color:blue;margin-left:20px"><!-- INLINE Stylesheet style keyword as an attribute-->
This page uses inline css using style attribute<BR/>
Inline Style Sheet has the highest priority amomg all style sheets<BR/>
Text color is blue and margin left width is 20px.
</p>
</body>
</html>
STYLE RULE CASCADING:
*{ font-weight : bold } applies to every element of HTML
#p1, #p3 { background-color : aqua }
#p3{ font-weight : normal }
What if more than one style declaration applies to a property of an element?
Multiple declaration
Browser applies rule cascading
A multistage sorting process that selects a single declaration that supply the property value
The CSS rule cascade determines which style rules declaration applies
Once declaration identified, associate origin and weight with every declaration
o PERSON WHO WROTE THE DOCUMENT

o PERSON WHO IS VIEWING THE DOCUMENT


o PERSON WHO WROTE THE BROWSER SOFTWARE
Origin of a declaration is one of the following:
o Author-> declaration is part of an external or embed style sheet or part of the value
o
o

specified by style attribute


User agent >A browser define default style property values for HTML elements
User-> Modern browsers allow users to provide a style sheet

User style rules defined in two ways:


o Edit|Preferences|Appearance, Fonts and colors panels allow a user to select various

style options
o User can explicitly create a style sheet file the browser will input when it is started
o Features provided by IE6
o Tools|Internet Options
Two weight values
o Normal
o Important
User/important highest priority in CSS to accommodate users with special needs
o Rules made important by adding !important:

Cascading order
What style will be used when there is more than one style specified for an HTML element?
All the styles will "cascade" into a new "virtual" style sheet by the following rules, where number
four has the highest priority:
Browser default
External style sheet
Internal style sheet (in the head section)
Inline style (inside an HTML element)
So, an inline style (inside an HTML element) has the highest priority, which means that it
will override a style defined inside the <head> tag, or in an external style sheet, or in a browser (a
default value).
Note: If the link to the external style sheet is placed after the internal style sheet in HTML
<head>, the external style sheet will override the internal style sheet!
STYLE INHERITANCE:
Cascading based on structure of style sheets
Inheritance based on tree structure of document
What if no style declaration applies to a property of an element?
Generally, the property value is inherited from the nearest ancestor element that has a value forthe
property
If no ancestor has a value (or the property does not inherit) then CSS defines an initial value that
is used
Property values:
o Specified: value contained in declaration
Absolute: value can be determined without reference to context (e.g., 2cm)
Relative: value depends on context (e.g., larger)
o Computed: browser performs calculation depends on particular relative value
o absolute representation of relative value (e.g., larger might be 1.2 x parent font size)
o Actual: value actually used by browser (e.g., computed value might be rounded)

3.CSS BOX MODEL


Each element of HTML , if is rendered visually occupies a rectangular area a Box
Every box consists conceptually of a nested collection of rectangular subareas
Innermost rectangular Content area (actual content of the element)
Padding separates the content area from the boxs border
Margin surrounding the border
Content and margin edges not displayed in the browser(inner and outer edges of the box)
Outer edge define box width and height, inner edge define content width and height
Every rendered element occupies a box:

CSS property names corresponding to 12 distances between adjacent edges in the box model

Box Model shorthand properties


PADDING:

BORDER:

POSITIONING METHODS IN CSS.


The CSS positioning properties allow you to position an element. It can also place an Element
behind another, and specify what should happen when an element's content is too big. Elements can be
positioned using the top, bottom, left, and right properties. However, these properties will not work
unless the position property is set first. They also work differently depending on the positioning method.
There are four different positioning methods.
Static Positioning:
HTML elements are positioned static by default. A static positioned element is always positioned
according to the normal flow of the page. Static positioned elements are not affected by the top,
bottom, left, and right properties.
Fixed Positioning
An element with fixed position is positioned relative to the browser window. It will not move even if the
window is scrolled:
Example:

p.pos_fixed
{
position:fixed;
top:30px;
right:5px;}
Note: Internet Explorer supports the fixed value only if a !DOCTYPE is specified.Fixed positioned
elements are removed from the normal flow. The document and other elements behave like the fixed
positioned element does not exist. Fixed positioned elements can overlap other elements.
Relative Positioning
A relative positioned element is positioned relative to its normal position.
Example
h2.pos_left
{
position:relative;
left:-20px;
}
h2.pos_right
{
position:relative;
left:20px;
}
The content of a relatively positioned elements can be moved and overlap other elements, but the reserved
space for the element is still preserved in the normal flow.
Example
h2.pos_top
{
position:relative;
top:-50px;
}
Relatively positioned element are often used as container blocks for absolutely positioned elements.
Absolute Positioning
An absolute position element is positioned relative to the first parent element that has a Position other
than static. If no such element is found, the containing block is <html>: Example
h2
{
position:absolute;
left:100px;
top:150px;
}
Absolutely positioned elements are removed from the normal flow. The document and other elements
behave like the absolutely positioned element does not exist.Absolutely positioned elements can overlap
other elements.

Float positioning
Float property none, left, and right
Moves the element box to far left or right

OBJECTS:

An object is a set of properties


A property consists of a unique (within an object) name with an associated value
The type of a property depends on the type of its value and can vary dynamically
Object properties do not have data types
Ex: Single property prop of an object o

There are no classes in JavaScript


Object constructors defined to create objects and automatically define properties for the objects
created
Instead, properties and methods can be created and deleted dynamically

Objects are created using new expression


First line creates a variable named o1 initialize its value of type object by calling built-in
constructor Object()
Second line adds a property named testing to the o1 object and assigns a string
value to this property
A constructor is a functionConstructor performs initialization on the object
Can add properties and methods to object
Can add object to an inheritance hierarchy from which it can inherit additional
properties and methods
The Object() built-in constructor
Does not add any properties or methods directly to the object
default toString() and valueOf() methods (used for conversions to String and
Number, resp.)
Assign a value to an object property
Property with the given name is created in the object and assigned the specified value
delete used to remove a property from an object
delete o1.testing;
Object initializer notation can be used to create an object (using Object()
constructor) and one or more properties in a single statement
Enumerating Properties
To know which property an object has at any given time
Special form of for statement used to iterate through all properties of an object:

Array notation
To print the values of those properties
The JavaScript object dot notation is actually shorthand for a more general associative array
notation in which Strings are array indices:
Expressions can supply property names:
Two different notations for accessing properties
Dot notation
Array reference syntax index is viewed as string value hash
Object can be viewed as a sort of array in which the elements are indexed by strings called
associative array
Object reference
StringBuffer s1 = new StringBuffer(Hello);
StringBuffer s2 = s1;
Single StringBuffer is created and both s1 and s2 will be references to it
Copies the reference from s1 to s2
If code followed by s2. append(World!);
System.out.println(s1);
Output: Hello World!.

Methods
JavaScript functions are stored as values of type Object
A function declaration creates a function value and stores it in a variable (property of
window) having the same name as the function
A method is an object property for which the value is a function
ARRAY
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables
could look like this:
var car1 = "Saab";
var car2 = "Volvo";
var car3 = "BMW";

Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
var array-name = [item1, item2, ...];
Example:
var cars = ["Saab", "Volvo", "BMW"];
Using the JavaScript Keyword new
The following example also creates an Array, and assigns values to it:
Example:
var cars = new Array("Saab", "Volvo", "BMW");
Access the Elements of an Array
You refer to an array element by referring to the index number.
This statement access the value of the first element in myCars:
var name = cars[0];
This statement modifies the first element in cars:
cars[0] = "Opel";
Note [0] is the first element in an array. [1] is the second. Array indexes start with 0.
Different Objects in One Array
JavaScript variables can be objects. Arrays are special kinds of objects.
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can have arrays in an
Array:
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
Arrays are Objects
Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for
arrays.But, JavaScript arrays are best described as arrays. Arrays use numbers to access its
"elements". In this example, person[0] returns John:
Array: var person = ["John", "Doe", 46];
Object: var person = {firstName:"John", lastName:"Doe", age:46};
Array Properties and Methods
The real strength of JavaScript arrays are the built-in array properties and methods:
Examples
var x = cars.length;
// The length property returns the number of elements in cars
var y = cars.sort();
// The sort() method sort cars in alphabetical order
The length Property
The length property of an array returns the length of an array (the number of array
elements).Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length;
// the length of fruits is 4
Adding Array Elements
The easiest way to add a new element to an array is to use the length property:
Example

var fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits
Adding elements with high indexes can create undefined "holes" in an array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[10] = "Lemon";
// adds a new element (Lemon) to fruits
Looping Array Elements
The best way to loop through an array is using a standard for loop:
Example
var index; var fruits = ["Banana", "Orange", "Apple", "Mango"];
for
(index = 0; index < fruits.length; index++)
{ text += fruits[index]; }

Dynamically changing Array length


Properties to an array can be added.
Changing the number of elements
Elements can be removed by decreasing
the value of length property
Creates an array with length 200 but does not

create or initialize the properties


Value of length is not necessarily the same as the actual number of elements
Array methods

JAVASCRIPT PROGRAM TO FIND FACTORIAL OF A GIVEN NUMBER


<html>
<body>
<script type = "text/javascript">
var n = parseInt(window.prompt("Enter the Number:"));
var result = fact(n);
window.alert("Factorial of the given number " + result);
function fact(n)
{
if(n == 0)
return 1;
else
return (n*fact(n-1));
}
</script>
</body>
</html>
JAVASCRIPT PROGRAM TO FIND LARGEST AMONG FIVE NUMBERS
<html>
<head>
<script language="javascript" type="text/javascript">
var number1, number2, number3,number4, number5,largest;
largest = number1 = window.prompt("Please input first number", 0);
number2 = window.prompt("Please input second number", 0);

number3 = window.prompt("Please input third number", 0);


number4 = window.prompt("Please input fourth number", 0);
number5 = window.prompt("Please input fifth number", 0);
if ( number2 > largest )
largest = number2;
if (number3 > largest)
largest = number3;
if (number4 > largest)
largest = number4;
if (number5 > largest)
largest = number5;
document.write("The largest number among " + number1 + ", " + number2
+ ", " + number3 + ", " + number4 + ", and " + number5 + " is " + largest + "<br />");
</script>
</head>
<body>
<p>Click refresh to reload JavaScript</p>
</body>
</html>
JAVASCRIPT PROGRAM TO FIND SUM OF FIRST N EVEN NUMBER
<html>
<head>
<script type=text/javascript>
Function series()
{
var i=0
var n=document.f1.t1.value;
while(i<=n)
{
document.write(i+<br>);
i=i+2;
}
}
</script>
</head>
<body>
<form name=f1>
Enter the value of n:<input type=text name=t1/>
<input type=button value=Sum of even nos onclick=series()/>

</form>
</body>
</html>

Regular Expression:
1. Checking first char is a digit
Var name=3abc;
var re=new RegExp("^[0-9]");
if(re.test(name))
{
xyz.innerText="User name should not start with a digit";
f1=0;
}
2. Checking valid email id
Var name=aa@a.c;
var re2=new RegExp("/^[a-zA-Z0-9][a-zA-Z0-9-_\s]+@[a-zA-Z0-9-\s].+\.[a-zA-Z]{2,5}$/");
if(!re2.test(name))
{
def.innerText="invalid id";
f1=0;
}
3. Checking given i/p is number.
Var name=abc;
var ae=new RegExp("[0-9]");
if(!ae.test(name))
{
hij.innerText="Field should contain only number";
f1=0;
}
4. Checking given i/p is CHAR.
Var name=123;
var ae=new RegExp("^[a-zA-Z ]");
if(!ae.test(name))
{
hij.innerText="Field should contain only char";
f1=0;
}

Das könnte Ihnen auch gefallen