Docstoc

GTU MCA PPT WTAD Unit-1 By Keval

Document Sample
GTU MCA PPT WTAD Unit-1 By Keval Powered By Docstoc
					Web Technology & Application
   Development (WTAD)

      Developed By:- Keval Nagaria




             Keval Nagaria           1
Unit:-1




 Keval Nagaria   2
Contents
 Introduction to HTML – only basic structure and tags (up
 to table tag) of HTML
 Overview of Java Script
 Primitives
 Date and Time,
 Operations and Expressions
 Screen Output and Keyboard Input
 Control Statement
 Object Creation and Modification
 Arrays
 Functions
 Constructors

                        Keval Nagaria                       3
HTML




Keval Nagaria   4
Markup Languages

Language   Year Introduced Description
SGML       1986             International standard for specifying
                            a document markup language
HTML       1992             An early recommendation
HTML+      1993             A superset of HTML
HTML 2.0   1995             An HTML version created by IETF
HTML 3.2   1996             W3C formal recommendation for
                            HTML
XML        1998             Universal format for structured
                            documents and data on the Web
XHTML      2000             Document markup language for the
                            Web

                       Keval Nagaria                                5
Introduction To HTML
 What is HTML ?
   The language used to develop web pages is
    called Hyper Text Markup Language(HTML).
   HTML is the language interpreted by a
    browser.
   Web pages are also called HTML documents.

   HTML is a set of special codes that can be
    embedded in text to add formatting and linking
    information.
   HTML is specified as TAGS in an HTML
    document(i.e The web Page)
                     Keval Nagaria                   6
Cont…
  HTML is very easy to use. Web documents are
   typically written in HTML using any test editor
   such as Windows Notepad and are usually
   named with the suffix(extension) .html or .htm
  HTML documents are standard ASCII files
   with formatting codes that contain information
   about layout (text styles , document titles,
   paragraphs, lists) and links.
  After entering the HTML code in a file you can
   view it using any browser.
  NOTE:- Same web page might be interpreted
   differently by different browsers.
                    Keval Nagaria                    7
Tools
 Browsers
   Internet Explorer
   Netscape Navigator

   Firefox

 Editors
     Text Editors
          Notepad(Windows), vi(Linux/Unix), Macintosh.
     Word Processors
          Microsoft Word, Word Perfect, Word Pro, AmiPro.
     HTML Editors
          Hotdog Pro, Web Weaver.
     Visual Editors
          Microsoft FrontPage, Netscape Composer, Adobe Page Mill, Dream
           Weaver(Macromedia).
                                      Keval Nagaria                         8
Structure of an HTML
 Element Tag
 Attributes
 Special Character
 Comments
 A complete HTML 4.0 Document
 Validating your HTML Tag




               Keval Nagaria    9
HTML Element / Tag
             <p align=“right”></p>


   Element    Attribute Name            Attribute Value



 You have to understand the important terms
 related to HTML.
 Not case-sensitive.


                        Keval Nagaria                     10
Main HTML Elements
 DOCTYPE
 HTML
 HEAD
  TITLE element required
  Optional Element
      BASE
      META

      BGSOUND

      SCRIPT

      NOSCRIPT

      STYLE

      LINK        Keval Nagaria   11
Cont…
 BODY Element
  <BODY BGCOLOR=“black”>
  HTML Attributes and Attributes Value
      BACKGROUND
      BGCOLOR

      TEXT

      LINK,VLINK,ALINK

      OnLoad,OnUnload,OnFocus,OnBlur

 Element Inside BODY Element
    <BODY>
     Remaining HTML Element
     </BODY>        Keval Nagaria         12
Block-Level Elements
 Headings
   H1….H6
   ALIGN

 Basic Text Sections
   P
   ALIGN

   PRE

   WIDTH

   ADDRESS

   BLOCKQOUTE

                  Keval Nagaria   13
Cont…
 Lists
  OL
  LI

  UL
  LI

  DL

  DT

  DD

 Frames And Forms

               Keval Nagaria   14
Cont…
 Misc.
  HR
  DIV

  CENTER

  MULTICOL(Netscape Only)




                Keval Nagaria   15
Headings
 Heading Types
     <H1 ...> ... </H1>
     <H2 ...> ... </H2>
     <H3 ...> ... </H3>
     <H4 ...> ... </H4>
     <H5 ...> ... </H5>
     <H6 ...> ... </H6>
 Attributes: ALIGN
     Values: LEFT (default), RIGHT, CENTER
 Nesting tags
     Headings and other block-level elements can contain
      text-level elements, but not vice versa

                           Keval Nagaria                    16
 Heading Example
<HTML>
<HEAD>
  <TITLE>Document Headings</TITLE>
</HEAD>
<BODY>
Samples of the six heading types:
<H1>Level-1 (H1)</H1>
<H2 ALIGN="CENTER">Level-2 (H2)</H2>
<H3><U>Level-3 (H3)</U></H3>
<H4 ALIGN="RIGHT">Level-4 (H4)</H4>
<H5>Level-5 (H5)</H5>
<H6>Level-6 (H6)</H6>
</BODY>
</HTML>




                           Keval Nagaria   17
P – The Basic Paragraph
 Attributes: ALIGN
     LEFT (default), RIGHT, CENTER. Same as headings.
     Whitespace ignored (use <BR> for line break)
          Consecutive <P>‟s do not yield multiple blank lines
     End Tag is Optional:

  <BODY>                         <BODY>
  <P>                            Paragraph 1
  Paragraph 1                    <P>
  </P>                           Paragraph 2
  <P>                            <P>
  Paragraph 2                    Paragraph 3
  </P>                           </BODY>
  <P>                            Equivalent with Implied Tags
  Paragraph 3
  </P>
  </BODY>
  Fully-Specified                 Keval Nagaria                  18
Preformatted Paragraphs
 The PRE Element
     <PRE> ... </PRE>
 Attributes: WIDTH
     Expected width in characters. Not widely supported.
 Problem: Special Characters
  <PRE>
  if (a<b) {
    doThis();
  } else {
    doThat();
  }
  </PRE>

                          Keval Nagaria                     19
 Desired Character        HTML Required
<                        &lt;
>                        &gt;
&                        &amp;
"                        &quot;
Non-breaking space       &nbsp;




                Keval Nagaria             20
HTML Character Entities
 The “<“ character has special meaning in
 HTML documents
   We cannot use it directly in the text.
   We have to use a character entity.

   We must use “&lt;” or “&#60;”

   Note, they are case sensitive.

   The most common one is the non-breaking
    space – “&nbsp;”




                    Keval Nagaria             21
The most common entities

Display   Description           Name
          Non-breaking          &nbsp;
          space
<         Less than             &lt;
>         Greater than          &gt;
&         Ampersand             &amp;
“         Quotation mark        &quot;
„         Apostrophe            &#39;



                Keval Nagaria            22
HTML Lists
 Unordred Lists
 Ordered Lists
 Definition Lists




                    Keval Nagaria   23
OL: Ordered (Numbered) Lists
 OL Element
     <OL>
        <LI>…
        <LI>…
        ...
      </OL>
     Attributes: TYPE, START, COMPACT
 List entries: LI
     <LI ...> ... </LI> (End Tag Optional)
     Attributes: (When inside OL) VALUE, TYPE




                           Keval Nagaria         24
UL: Unordered (Bulleted) Lists
 UL Element
     <UL>
       <LI>…
       <LI>…
       ...
      </UL>
 Attributes: TYPE, COMPACT
     TYPE is DISC, CIRCLE, or SQUARE
 List entries: LI (TYPE)
     TYPE is DISC, CIRCLE, or SQUARE




                           Keval Nagaria   25
Text-Level Elements
 Physical Character Styles
     B, I, TT, U, SUB, SUP, SMALL, BIG, STRIKE, S, BLINK
     FONT
          SIZE
          COLOR
          FACE
     BASEFONT
     SIZE
 Logical Character Styles
     EM, STRONG, CODE, SAMP, KBD, DFN, VAR, CITE




                           Keval Nagaria                    26
Cont…
 Hypertext Links
    A
         HREF, NAME, TARGET, ...
 Images
    IMG
         SRC (required), ALT, ALIGN, WIDTH, HEIGHT, HSPACE,
          VSPACE, BORDER, USEMAP, ISMAP
 Misc. Text-Level Elements
    BR (Explicit line break)
    AREA (Client-side image maps)
    APPLET (Java)
    ...



                          Keval Nagaria                        27
OL Example
 <OL TYPE="I">
   <LI>Headings
   <LI>Basic Text Sections
   <LI>Lists
       <OL TYPE="A">
         <LI>Ordered
             <OL TYPE="1">
                <LI>The OL tag
                    <OL TYPE="a">
                      <LI>TYPE
                      <LI>START
                      <LI>COMPACT
                    </OL>
                <LI>The LI tag
             </OL>
         <LI>Unordered
             <OL TYPE="1">
                <LI>The UL tag
                <LI>The LI tag
             </OL>
         <LI>Definition
             <OL TYPE="1">
                <LI>The DL tag
                <LI>The DT tag
                <LI>The DD tag
             </OL>
       </OL>
   <LI>Miscellaneous
 </OL>

                                    Keval Nagaria   28
UL Example
     <UL TYPE="DISC">
       <LI>The UL tag
           <UL TYPE="CIRCLE">
             <LI>TYPE
               <UL TYPE="SQUARE">
                 <LI>DISC
                 <LI>CIRCLE
                 <LI>SQUARE
               </UL>
             <LI>COMPACT
           </UL>
       <LI>The LI tag
           <UL TYPE="CIRCLE">
             <LI>TYPE
               <UL TYPE="SQUARE">
                 <LI>DISC
                 <LI>CIRCLE
                 <LI>SQUARE
               </UL>
             <LI>VALUE
           </UL>
     </UL>

                    Keval Nagaria   29
Physical Character Styles Example
...
<H1>Physical Character Styles</H1>
<B>Bold</B><BR>
<I>Italic</I><BR>
<TT>Teletype (Monospaced)</TT><BR>
<U>Underlined</U><BR>
Subscripts: f<SUB>0</SUB> + f<SUB>1</SUB><BR>
Superscripts: x<SUP>2</SUP> + y<SUP>2</SUP><BR>
<SMALL>Smaller</SMALL><BR>
<BIG>Bigger</BIG><BR>
<STRIKE>Strike Through</STRIKE><BR>
<B><I>Bold Italic</I></B><BR>
<BIG><TT>Big Monospaced</TT></BIG><BR>
<SMALL><I>Small Italic</I></SMALL><BR>
<FONT COLOR="GRAY">Gray</FONT><BR>
<DEL>Delete</DEL><BR>
<INS>Insert</INS><BR>
...




                             Keval Nagaria        30
Logical Character Style‟s Example
...
<H1>Logical Character Styles</H1>
<EM>Emphasized</EM><BR>
<STRONG>Strongly Emphasized</STRONG><BR>
<CODE>Code</CODE><BR>
<SAMP>Sample Output</SAMP><BR>
<KBD>Keyboard Text</KBD><BR>
<DFN>Definition</DFN><BR>
<VAR>Variable</VAR><BR>
<CITE>Citation</CITE><BR>
<EM><CODE>Emphasized Code</CODE></EM><BR>
<FONT COLOR="GRAY"><CITE>Gray Citation</CITE></FONT><BR>
<ACRONYM TITLE="Java Development Kit">JDK
   Acronym</ACRONYM>
...




                         Keval Nagaria                     31
Text Formatting

<b>               Bold text
<big>             Big text
<em>              Emphasized text
<i>               Italic text
<small>           Small text
<strong>          Strong text
<sub>             Subscripted text
<sup>             Superscripted text



             Keval Nagaria             32
HTML Links
 <a> to create a link to another document.
 The target attribute
  <a href=“…”, target=“_blank”>xxx</a>
  Open the document in a new browser window.

 The name attribute
  <a name=“abc”>
  <a href=“#abc”>Useful text</a>




                   Keval Nagaria                33
Hypertext Links
 Links can contain images and other text-level elements
 (i.e., <A HREF…> ... </A>)
 Link to Absolute URL
     Use a complete URL beginning with http://
       Java is discussed in
       <A HREF="http://host/path/chapter2.html">
       Chapter 2</A>.

 Link to Relative URL
     Use a filename or relative path to filename
        Interpreted wrt location of current file
       Java is discussed in
       <A HREF="chapter2.html">Chapter 2</A>.




                               Keval Nagaria              34
Cont…
 Link to Section
    Use a section name (see below) preceded by #
      Images are discussed in
      <A HREF="#Section2">Section 2</A>.


 Link to Section in URL
    Use absolute or relative URL, then #, then section name
      Images are discussed in
      <A HREF="chapter1.html#Section2">
      Sec. 2 of Chap. 1</A>.
 Naming a Section
    Use <A NAME="..."> and do not include the pound sign
      <H2><A NAME="Section2">Images</A></H2>




                             Keval Nagaria                     35
      Link Example
<html>
                                                                                Text between strong tags will
   <head>                                                                               appear bold.
     <title>Internet and WWW How to Program - Links</title>
   </head>

   <body>
                                                                          Linking is accomplished in XHTML
                                                                              with the anchor (a) element.
     <h1>Here are my favorite sites</h1>

     <p><strong>Click on a name to go to that page.</strong></p>
                                                                          The text between the a tags is the
     <p><a href = "http://www.kevalnagaria.blogspotcom">Keval</a></p>            anchor for the link.
     <p><a href = "http://www.kevalnagaria.blogspotcom">Nagaria</a></p>

     <p><a href = "http://www.gtumcappt.blogspot.com">MySite</a></p>

     <p><a href = "http://www.kevalnagaria.blogspotcom">My</a></p>

   </body>
 </html>
                                                                           The anchor links to the page that‟s
                         Elements placed between paragraph tags            value is given by the href attribute.
                        will be set apart from other elements on the
                        page with a vertical line before and after it.
                                                     Keval Nagaria                                         36
IMG: Embedding Images
 Example
 <IMG SRC="SomeFile.gif" ALT="My Dog"
      WIDTH=400 HEIGHT=300>
 Attributes:
    SRC (required)
    ALT (technically required)
    ALIGN (see <BR CLEAR="ALL">)
    WIDTH, HEIGHT
    HSPACE, VSPACE
    BORDER
    USEMAP, ISMAP



                    Keval Nagaria       37
Image Alignment Example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE>Image Alignment</TITLE></HEAD>
<BODY>
<H1 ALIGN="CENTER">Image Alignment</H1>
<TABLE BORDER=1>
  <TR><TH>Alignment
      <TH>Result
  <TR><TH><CODE>LEFT</CODE>
      <TD><IMG SRC="rude-pc.gif" ALIGN="LEFT"
               ALT="Rude PC" WIDTH=54 HEIGHT=77>
          This positions the image at the left side,
          with text flowing around it on the right.
 <TR><TH><CODE>RIGHT</CODE>
      <TD><IMG SRC="rude-pc.gif" ALIGN="RIGHT"
               ALT="Rude PC" WIDTH=54 HEIGHT=77>
          This positions the image at the right side,
          with text flowing around it on the left.
   ...
</TABLE>
</BODY>
</HTML>


                                Keval Nagaria                    38
Tables
 Template
  <TABLE BORDER=1>
    <CAPTION>Table Caption</CAPTION>
    <TR><TH>Heading1</TH>      <TH>Heading2</TH></TR>
    <TR><TD>Row1 Col1 Data</TD><TD>Row1 Col2 Data</TD></TR>
    <TR><TD>Row2 Col1 Data</TD><TD>Row2 Col2 Data</TD></TR>
    <TR><TD>Row3 Col1 Data</TD><TD>Row3 Col2 Data</TD></TR>
  </TABLE>




                         Keval Nagaria                        39
TABLE Element Attributes
 ALIGN
     The ALIGN attribute gives the horizontal alignment of the table as
      a whole
     Legal values are LEFT, RIGHT, and CENTER, with LEFT being
      the default
 BORDER
     This specifies the width in pixels of the border around the table
     This is in addition to the border around each cell (the
      CELLSPACING).
     The default is zero, which also results in the visible 3D divider
      between cells being turned off
 CELLSPACING
     This gives the space in pixels between adjacent cells. Drawn as a
      3D line if BORDER is nonzero, otherwise empty space in the
      background color is used
     The default is usually about 3

                               Keval Nagaria                               40
Cont…
 CELLPADDING
    CELLPADDING determines the empty space, in pixels, between
     the cell‟s border and the table element
    The default is usually about 1
 WIDTH
    This specifies the width of the table, either in pixels (<TABLE
     WIDTH=250>) or as a percentage of the current browser window
     width (<TABLE WIDTH="75%">)
 BGCOLOR
    Specify the background color of the table TABLE (also legal for
     TR, TD, and TH)
 BORDERCOLOR, BORDERCOLORDARK,
 BORDERCOLORLIGHT
    Non standard attributes supported by IE to specify the colors to
     user for the borders


                              Keval Nagaria                             41
Cont…
 BACKGROUND
    This nonstandard attribute supported by IE gives an image file that
     will be tiled as the background of the table
    You might want to use style sheets instead.
 RULES
    HTML 4.0 attribute that specifies which inner dividing lines are
     drawn
    All are drawn if this attribute is omitted
    Legal values are NONE, ROWS, COLS, and ALL
 FRAME
    Specifies which outer borders are drawn
    All four are drawn if this attribute is omitted
    Legal values are BORDER or BOX (all), VOID (none), ABOVE
     (top), BELOW (bottom), HSIDES (top and bottom, despite the
     somewhat confusing name), VSIDES (left and right), LHS (left),
     and RHS (right)

                              Keval Nagaria                                42
Table CAPTION
 Attribute
    ALIGN (Values: TOP, BOTTOM)
 Usage
    An enclosing borderless table may give more flexibility
     than the built-in CAPTION.




                         Keval Nagaria                         43
TR: Table Row
 TR is used to define each row in the table
 Each row will then contain TH and/or TD entries
 ALIGN
    ALIGN (legal values LEFT, RIGHT, or CENTER) is used to set
     the default horizontal alignment for table cells
 VALIGN
    VALIGN (legal values TOP, MIDDLE, or BOTTOM) is used to
     set the default vertical alignment for table cells
 BGCOLOR
    Sets the color for the table row, overriding any values set for the
     table as a whole via the BGCOLOR attribute of TABLE
 BORDERCOLOR, BORDERCOLORDARK,
 BORDERCOLORLIGHT
    Supported only by Internet Explorer, these specify the colors to use
     for the row borders

                               Keval Nagaria                                44
Table Cells: TH and TD
 COLSPAN
     COLSPAN defines a heading or cell data entry that
      spans multiple columns

       <TABLE BORDER=1>
       <TR><TH COLSPAN=2>Col 1&2 Heading
             <TH>Col3 Heading
         <TR><TD>Col1 Data
             <TD>Col2 Data
             <TD>Col3 Data
       </TABLE>




                         Keval Nagaria                    45
Cont…
 ROWSPAN
    ROWSPAN defines a heading or cell data entry that spans multiple
     rows; similar to COLSPAN
 ALIGN
    LEFT, RIGHT, CENTER, JUSTIFY and CHAR.
    E.g., the following aligns entries on a decimal point
                  <TD ALIGN="CHAR" CHAR=".">
 VALIGN
    TOP, BOTTOM, MIDDLE
 WIDTH, HEIGHT
    Values in pixels only (no percentages officially allowed)
 NOWRAP
    Use with caution
 BGCOLOR, BACKGROUND
    Same as for TABLE and TR
                              Keval Nagaria                             46
HTML Hex-Colors
         White                    #FFFFFF
         Red                      #FF0000
         Green                    #00FF00
         Blue                     #0000FF
         Cyan                     #00FFFF
         Yellow                   #FFFF00
         Black                    #000000
         Dim Grev                 #545454
         Forest Green             #238E23
         Grey                     #C0C0C0
         Midnight Blue            #2F2F4F
         Orange                   #FF7F00
         Spring Green             #00FF7F
         Turquoise                #ADEAEA

                  Keval Nagaria             47
Basic HTML - Summary
 A DOCTYPE is required to validate the document
 HTML document should have an enclosing
 HTML element, a HEAD (TITLE is required) and
 a BODY
 Hypertext links, <A HREF="…">
    can be absolute or relative
    A link to a named section is denoted by #section
 Tables are composed of main table element,
 <TABLE>; rows, <TR>; table headers, <TH>;
 and table data, <TD>
    Use BGCOLOR to give background colors to tables,
     rows, or cells
    Use ROWSPAN or COLSPAN to join cells
                         Keval Nagaria                  48
JavaScript




  Keval Nagaria   49
Overview of java script
 The growth of the WWW has resulted
 in a demand for dynamic and
 interactive web sites.
 There are many different kinds of
 scripting languages – JavaScript, …
 This lecture aims at offering in-depth
 knowledge of JavaScript, discussing
 the complexity of scripting and
 studying various common examples.

                Keval Nagaria             50
JavaScript Capabilities
 Improve the user interface of a website
 Make your site easier to navigate
 Easily create pop-up alert, windows
 Replace images on a page without
 reload the page
 Form validation
 Many others …


                 Keval Nagaria             51
JavaScript Versions
 JavaScript 1.0
     Supported by Netscape 2.0 and IE 3.0
 JavaScript 1.1
     Supported by Netscape 3.0 and IE 4.0
 JavaScript 1.2
     Supported by Netscape 4.0 and IE 4.0
 JavaScript 1.3
     Supported by Netscape 4.5 and IE 5.0
 JavaScript 1.5
     Supported by Netscape 6.0 and IE 5.5 and later



                          Keval Nagaria                52
The Future of JavaScript
 ECMA standard brings JavaScript and Jscript
 together.
     ECMA - An International industry association
      dedicated to standardize information and
      communication systems.
 Both Netscape and Microsoft have pledged that
 they will support and develop JavaScript in the
 future.
 It is future-proof, and it is not going to disappear
 in the near future. 


                         Keval Nagaria                  53
A Simple Script
<html>
<head> <title>Keval Nagaria…</title> </head>
<body>
<h1>First JavaScript Page</h1>
<script type="text/javascript">
<!--
document.write("<hr>");
document.write("Hello…");
document.write(“Welocme to Keval Nagaria‟s world…”);
document.write("<hr>");
-->
</script>
</body>
</html>



                                Keval Nagaria          54
Embedding JavaScript

<html>
<head>
<title>First JavaScript Program</title>
</head>
<body>
<script language=“JavaScript”
   src=“your_source_file.js”></script>
</body>
</html>




                           Keval Nagaria   55
JavaScript Source File
<script language=“JavaScript”
src=“your_source_file.js”></script>
 SRC – specifies the location of an external script
 TYPE – specifies the scripting language of the
 script
 LANGUAGE – specifies the scripting language of
 the script
 TYPE and LANGUAGE have a similar function,
 we use LANGUAGE to specify the language used
 in the script
                     Keval Nagaria                    56
Need for a source file
 If the JavaScript code is fairly short, you are
 recommended to include the code in the
 HTML document.
 To add clarity to an HTML document.
 To share JavaScript code across multiple
 HTML documents.
 To help you hide your JavaScript code.
   Spent lot of time for JavaScript coding.
   Viewer can only see the location of the source
    file but not the contents.

                     Keval Nagaria                   57
Hide JavaScript from incompatible browsers

<script language=“JavaScript”>
<!– begin hiding JavaScript
// single-line comment, /* … */ multiple-line comment
End hiding JavaScript -->
</script>
<noscript>
Your browser does not support JavaScript.
</noscript>


    Not all browsers support JavaScript.
    E.g. NN1, IE2, character-based lynx.

                            Keval Nagaria               58
JavaScript confusion
JavaScript                             Java
Interpreted by the client-side         Compiled on the server before
computer                               executed on the client machine

Dynamic binding, object references     Static binding, object references
are checked at runtime                 must exist at compile time

No need to declare data types          Data types must be declared
Code is embedded in HTML               Code is not integrated in HTML
Limited by the browser                 Java applications are standalone
functionality

Can access browser objects             Java has no access to browser
                                       objects


                                 Keval Nagaria                             59
Using the alert() Method
<head>
<script language=“JavaScript”>
         alert(“An alert triggered by JavaScript”);
</script>
</head>


  It is the easiest methods to use amongst alert(),
  prompt() and confirm().
  You can use it to display textual information to the
  user (simple and concise).
  The user can simply click “OK” to close it.

                            Keval Nagaria                60
Using the confirm() Method
<head>
<script language=“JavaScript”>
         confirm(“Are you happy with the class?”);
</script>
</head>


  This box is used to give the user a choice either
  OK or Cancel.
  It is very similar to the “alert()” method.
  You can also put your message in the method.


                            Keval Nagaria             61
Using the promat() Method
<head>
<script language=“JavaScript”>
         prompt(“What is your student id number?”);
         prompt(“What is your name?”,”No name”);
</script>
</head>

  This is the only one that allows the user to type in
  his own response to the specific question.
  You can give a default value to avoid displaying
  “undefined”.


                           Keval Nagaria                 62
Three methods
   <script language="JavaScript">
   alert("This is an Alert method");
   confirm("Are you OK?");
   prompt("What is your name?");
   prompt("How old are you?","20");
   </script>




                          Keval Nagaria   63
Variables
 JavaScript allows you to declare and use
 variables to store values.
 How to assign a name to a variable?
   Include uppercase and lowercase letters
   Digits from 0 through 9
   The underscore _ and the dollar sign $
   No space and punctuation characters
   First character must be alphabetic letter or
    underscore – 99Total?, 012345number?, …
   Case-sensitive
   No reserved words or keywords

                     Keval Nagaria                 64
Which one is legal?

 My_variable
                                  Legal
 $my_variable
 1my_example
 _my_variable
 @my_variable
 My_variable_example
 ++my_variable
 %my_variable                     Illegal
 #my_variable
 ~my_variable
 myVariableExample
                  Keval Nagaria             65
Variable on-the-fly
<head>
<script language=“JavaScript”>
         var id;
         id = prompt(“What is your student id number?”);
         alert(id);
         name = prompt(“What is your name?”,”No name”);
         alert(name);
</script>
</head>


  We should use “var” because it is more easy
  to keep track of the variables.
                          Keval Nagaria                    66
Data Types
 JavaScript allows the same variable to contain
 different types of data values.
 Primitive data types
     Number: integer & floating-point numbers
     Boolean: logical values “true” or “false”
     String: a sequence of alphanumeric characters
 Composite data types (or Complex data types)
     Object: a named collection of data
     Array: a sequence of values
 Special data types
     Null: an initial value is assigned
     Undefined: the variable has been created by not yet
      assigned a value
                          Keval Nagaria                     67
Numeric Data Types
 It is an important part of any
 programming language for doing
 arithmetic calculations.
 JavaScript supports:
            A positive or negative number
   Integers:
   with no decimal places.
     Ranged    from –253 to 253
   Floating-pointnumbers: usually written
   in exponential notation.
     3.1415…,    2.0e11

                      Keval Nagaria          68
Integer and Floating-point number example

<script language=“JavaScript”>
       var integerVar = 100;
       var floatingPointVar = 3.0e10;
       // floating-point number 30000000000
       document.write(integerVar);
       document.write(floatingPointVar);
</script>

  The integer 100 and the number
  30,000,000,000 will be appeared in the
  browser window.
                      Keval Nagaria           69
Boolean Values
 A Boolean value is a logical value of
 either true or false. (yes/no, on/off)
 Often used in decision making and data
 comparison.
 In JavaScript, you can use the words
 “true” and “false” directly to indicate
 Boolean values.
 Named by the 19th century
 mathematician “George Boole”.

                Keval Nagaria              70
Boolean value example
<head>
<script language=“JavaScript”>
       var result;
       result = (true*10 + false*7);
       alert(“true*10 + false*7 = “, result);
</script>
</head>

   The expression is converted to
       (1*10 + 0*7) = 10
   They are automatically converted.
                         Keval Nagaria          71
Strings
 A string variable can store a sequence
 of alphanumeric characters, spaces and
 special characters.
 String can also be enclosed in single
 quotation marks („) or in double
 quotation marks (“).
 What is the data type of “100”?
   String   but not number type
 Pay attention to the special characters.

                     Keval Nagaria          72
Strings example
<head>
<script language=“JavaScript”>
         document.write(“This is a string.”);
         document.write(“This string contains „quote‟.”);
         var myString = “My testing string”;
         alert(myString);
</script>
</head>


  Unlike Java and C, JavaScript does not have
  a single character (char) data type.


                            Keval Nagaria                   73
typeof operator
<head>
<script language=“JavaScript”>
         var x = “hello”, y;
         alert(“Variable x value is “ + typeof(x));
         alert(“Variable y value is “ + typeof(y));
         alert(“Variable x value is “ + typeof(z));
</script>
</head>


   It is an unary operator.
       Return either: Number, string, Boolean, object,
        function, undefined, null
                             Keval Nagaria                74
What is an Object?
 An object is a thing, anything, just as things in the
 real world.
     E.g. (cars, dogs, money, books, … )
 In the web browser, objects are the browser
 window itself, forms, buttons, text boxes, …
 Methods are things that objects can do.
     Cars can move, dogs can bark.
     Window object can alert the user “alert()”.
 All objects have properties.
     Cars have wheels, dogs have fur.
     Browser has a name and version number.


                           Keval Nagaria                 75
Array
 An Array contains a set of data represented
 by a single variable name.
 Arrays in JavaScript are represented by the
 Array Object, we need to “new Array()” to
 construct this object.
 The first element of the array is “Array[0]”
 until the last one Array[i-1].
 E.g. myArray = new Array(5)
     We have myArray[0,1,2,3,4].



                      Keval Nagaria             76
Array Example
<script language=“JavaScript”>
         Car = new Array(3);
         Car[0] = “Ford”;
         Car[1] = “Toyota”;
         Car[2] = “Honda”;
         document.write(Car[0] + “<br>”);
         document.write(Car[1] + “<br>”);
         document.write(Car[2] + “<br>”);
</script>

   You can also declare arrays with variable length.
       arrayName = new Array();
       Length = 0, allows automatic extension of the length.
       Car[9] = “Ford”; Car[99] = “Honda”;

                                Keval Nagaria                   77
Null & Undefined
 An “undefined” value is returned when you
 attempt to use a variable that has not been
 defined or you have declared but you forgot
 to provide with a value.
 Null refers to “nothing”
 You can declare and define a variable as
 “null” if you want absolutely nothing in it,
 but you just don‟t want it to be “undefined”.




                   Keval Nagaria                 78
Null & Undefined example
<html>
<head>
<title> Null and Undefined example </title>
<script language=“JavaScript”>
           var test1, test2 = null;
           alert(“No value assigned to the variable” + test1);
           alert(“A null value was assigned” + test2);
</script>
</head>
<body> … </body>
</html>




                                    Keval Nagaria                79
JavaScript Special Characters
Character           Meaning
\b                  Backspace
\f                  Form feed
\t                  Horizontal tab
\n                  New line
\r                  Carriage return
\\                  Backslash
\‟                  Single quote
\”                  Double quote

              Keval Nagaria           80
Expressions
 It is a set of literals, variables,
 operators that merge and evaluate to a
 single value.
   Left_operand   operator right_operand
 By using different operators, you can
 create the following expressions.
   Arithmetic, logical
   String and conditional expressions.



                    Keval Nagaria           81
Operators
 Arithmetic operators
 Logical operators
 Comparison operators
 String operators
 Bit-wise operators
 Assignment operators
 Conditional operators

                Keval Nagaria   82
    Arithmetic operators
     left_operand “operator” right_operand
Operator      Name                  Description           Example
+             Addition              Adds the operands     3+5
-             Subtraction           Subtracts the right   5-3
                                    operand from the
                                    left operand
*             Multiplication        Multiplies the        3*5
                                    operands
/             Division              Divides the left      30 / 5
                                    operand by the
                                    right operand
%             Modulus               Calculates the        20 % 5
                                    remainder

                               Keval Nagaria                        83
Unary Arithmetic Operators
  Binary operators take two operands.
  Unary type operators take only one operand.
  Which one add value first, and then assign value
  to the variable?

Name                              Example
Post Incrementing operator        Counter++
Post Decrementing operator        Counter--
Pre Incrementing operator         ++counter
Pre Decrementing operator         --counter

                             Keval Nagaria           84
Logical operators
     Used to perform Boolean operations on Boolean
     operands


Operator       Name                Description        Example
&&             Logical and         Evaluate to “true” 3>2 && 5<2
                                   when both
                                   operands are true
||             Logical or          Evaluate to “true 3>1 || 2>5
                                   when either
                                   operand is true
!              Logical not         Evaluate to “true” 5 != 3
                                   when the
                                   operand is false
                             Keval Nagaria                         85
 Comparison operators
      Used to compare two numerical values
Operator       Name                          Description                      Example

==             Equal                         Perform type conversion          “5” == 5
                                             before checking the equality

===            Strictly equal                No type conversion before        “5” === 5
                                             testing

!=             Not equal                     “true” when both operands        4 != 2
                                             are not equal

!==            Strictly not equal            No type conversion before        5 !== “5”
                                             testing nonequality

>              Greater than                  “true” if left operand is        2>5
                                             greater than right operand

<              Less than                     “true” if left operand is less   3<5
                                             than right operand

>=             Greater than or equal         “true” if left operand is        5 >= 2
                                             greater than or equal to the
                                             right operand

<=             Less than or equal            “true” if left operand is less   5 <= 2
                                             than or equal to the right
                                             operand

                                       Keval Nagaria                                      86
Strict Equality Operators

<script language=“JavaScript”>
          var currentWord=“75”;
          var currentValue=75;
          var outcome1=(currentWord == currentValue);
          var outcome2=(currentWord === currentValue);
          alert(“outcome1: “ + outcome1 + “ : outcome2: “ + outcome2);
</script>


  Surprised that outcome1 is True!
  JavaScript tries very hard to resolve
  numeric and string differences.
                              Keval Nagaria                              87
String operator
    JavaScript only supports one string
    operator for joining two strings.

Operator          Name                Description   Return value
+                 String        Joins two           “HelloWorld”
                  concatenation strings

<script language=“JavaScript”>
          var myString = “”;
          myString = “Hello” + “World”;
          alert(myString);
</script>
                                 Keval Nagaria                     88
    Bit Manipulation operators
     Perform operations on the bit representation of a
     value, such as shift left or right.
Operator             Name                            Description

&                    Bitwise AND                     Examines each bit position

|                    Bitwise OR                      If either bit of the operands is
                                                     1, the result will be 1

^                    Bitwise XOR                     Set the result bit, only if
                                                     either bit is 1, but not both

<<                   Bitwise left shift              Shifts the bits of an
                                                     expression to the left

>>                   Bitwise signed right shift      Shifts the bits to the right,
                                                     and maintains the sign

>>>                  Bitwise zero-fill right shift   Shifts the bits of an
                                                     expression to right

                                Keval Nagaria                                           89
    Assignment operators
     Used to assign values to variables
Operator          Description                      Example
=                 Assigns the value of the right A = 2
                  operand to the left operand
+=                Add the operands and             A += 5
                  assigns the result to the left
                  operand
-=                Subtracts the operands and       A -= 5
                  assigns the result to the left
                  operand
*=                Multiplies the operands and      A *= 5
                  assigns the result to the left
                  operand
/=                Divides the left operands by     A /= 5
                  the right operand and assigns
                  the result to the left operand
%=                Assigns the remainder to the     A %= 2
                  left operand
                              Keval Nagaria                  90
The most common problem
<script language=“JavaScript”>
       if (alpha = beta) { … }
       if (alpha == beta) { … }
</script>


   Don‟t mix the comparison operator and the
   assignment operator.
   double equal sign (==) and the equal
   operator (=)


                       Keval Nagaria           91
Order of Precedence
 Precedence     Operator
 1              Parentheses, function calls
 2              , ~, -, ++, --, new, void, delete
 3              *, /, %
 4              +, -
 5              <<, >>, >>>
 6              <, <=, >, >=
 7              ==, !=, ===, !==
 8              &
 9              ^
 10             |
 11             &&
 12             ||
 13             ?:
 14             =, +=, -=, *=, …
 15             The comma (,) operator
              Keval Nagaria                         92
Precedence Example
Value =   (19 % 4) / 1 – 1 - !false
Value =   3 / 1 – 1 - !false
Value =   3 / 1 – 1 - true
Value =   3 – 1 - true
Value =   3–2
Value =   1

                 Keval Nagaria        93
Scope of a Variable
 When you use a variable in a
 JavaScript program that uses functions.
 A global scope variable is one that is
 declared outside a function and is
 accessible in any part of your program.
 A local variable is declared inside a
 function and stops existing when the
 function ends.


                Keval Nagaria              94
    Example of variable, data types
<html><head><title> Billing System of Web Shoppe </title></head><body>
<h1 align="center"> Billing System of Web Shoppe </h1>
<script language="JavaScript">
firstCustomer = new Array();
billDetails = new Array(firstCustomer);
var custName, custDob, custAddress, custCity, custPhone;
var custAmount, custAmountPaid, custBalAmount;
custName=prompt("Enter the first customer's name:", "");
custDob=prompt("Enter the first customer's date of birth:", "");
custAddress=prompt("Enter the first customer's address:", "");
custPhone=prompt("Enter the first customer's phone number:", "");
custAmount=prompt("Enter the total bill amount of the first customer:", "");
custAmountPaid=prompt("Enter the amount paid by the first customer:", "");
custBalAmount = custAmount - custAmountPaid;
firstCustomer[0]=custName;
firstCustomer[1]=custDob;
firstCustomer[2]=custAddress;
firstCustomer[3]=custPhone;
firstCustomer[4]=custBalAmount;
document.write("<B>" + "You have entered the following details for first customer:" + "<BR>");
document.write("Name: " + billDetails[0][0] + "<BR>");
document.write("Date of Birth: " + billDetails[0][1] + "<BR>");
document.write("Address: " + billDetails[0][2] + "<BR>");
document.write("Phone: " + billDetails[0][3] + "<BR>");
     (custBalAmount == 0) ? document.write("Amount Outstanding: " + custBalAmount):document.write("No amount due")
</script></body></html>



                                                          Keval Nagaria                                              95
Conditional Statement
 “if” statement
 “if … else” statement
 “else if” statement
 “if/if … else” statement
 “switch” statement



               Keval Nagaria   96
“if” statement
    if (condition) { statements; }

 It is the main conditional statement in
 JavaScript.
 The keyword “if” always appears in
 lowercase.
 The condition yields a logical true or false
 value.
 The condition is true, statements are
 executed.
                   Keval Nagaria                97
 “if” statement example

<script language=“JavaScript”>
var chr = “”;
…
if (chr == „A‟ || chr == „O‟) {
       document.write(“Vowel variable”);
}
</script>

        “||” operator - increase the speed of the script



                                 Keval Nagaria             98
“if … else” statement

   if (condition) { statements; }
   else { statements; }


 You can include an “else” clause in an if
 statement when you want to execute some
 statements if the condition is false.



                  Keval Nagaria              99
 Ternary Shortcut (concise)
<script language=“JavaScript”>
If (3 > 2) {
        alert(“True”);
} else {
        alert(“False”);
}

(3 > 2) ? alert(“True”) : alert(“False”);
</script>


    Substitute for a simple “if/else” statement.
                          Keval Nagaria            100
“else if” statement

    if (condition) { statement; }
    else if (condition) { statement; }
    else { statement; }

 Allows you to test for multiple expression
 for one true value and executes a particular
 block of code.


                   Keval Nagaria                101
“if/if…else” statement example
<script language=“JavaScript”>
var chr;
chr = prompt(“Please enter a character : “,””);
if (chr >= „A‟){
   if (chr <= „Z‟)
        alert(“Uppercase”);
   else if (chr >= „a‟){
        alert(“Lowercase”);
   }
}
</script>

                        Keval Nagaria             102
“switch” statement
    switch (expression) {
          case label1:
                 statements; break;
          default:
                 statements;
    }


 Allows you to merge several evaluation
 tests of the same variable into a single block
 of statements.
                    Keval Nagaria                 103
  “switch” statement example
<script language=“JavaScript”>
var chr;
chr = prompt(“Pls enter a character in lowercase:”,””);
switch(chr){
         case „a‟ :
                  alert(“Vowel a”); break;
         case „e‟ :
                  alert(“Vowel e”); break;
         default :
                  alert(“Not a vowel”);
}
</script>



                               Keval Nagaria              104
Looping Statement
 “for” Loops
 “for/in” Loops
 “while” Loops
 “do … while” Loops
 “break” statement
 “continue” statement

               Keval Nagaria   105
“for” statement
   for (initial_expression; test_exp; change_exp)
   { statements; }

 One of the most used and familiar loops is
 the for loop.
 It iterates through a sequence of statements
 for a number of times controlled by a
 condition.
 The change_exp determines how much has
 been added or subtracted from the counter
 variable.
                    Keval Nagaria                   106
“for” statement example
<script language=“JavaScript”>
var counter;
for (counter = 1; counter <= 10; counter++)
{
       document.write(counter*counter + “ “);
}
</script>

   Display the square of numbers
   Output: 1 4 9 16 25 36 49 64 81 100

                        Keval Nagaria           107
“for/in” statement
      for (counter_variable in object)
      { statements; }


 When the for/in statement is used, the counter and
 termination are determined by the length of the
 object.
 The statement begins with 0 as the initial value of
 the counter variable, terminates with all the
 properties of the objects have been exhausted.
     E.g. array  no more elements found


                         Keval Nagaria                 108
 “for/in” statement example
<script language=“JavaScript”>
var book; (What is the difference if “var book=“”;)
var booklist = new Array(“Chinese”, “English”, “Jap”);
for (var counter in booklist) {
       book += booklist[counter] + “ “;
}
alert(book);
</script>




                         Keval Nagaria                   109
“while” statement
    initial value declaration;
    while (condition) {
            statements;
            increment/decrement statement;
    }

 The while loop begins with a termination
 condition and keeps looping until the
 termination condition is met.
 The counter variable is managed by the
 context of the statements inside the curly
 braces.
                   Keval Nagaria              110
 “While” statement example
<html>
<head>
<title>While loop example</title>
<script language=“JavaScript”>
var counter = 100;
var numberlist = “”;
while (counter > 0) {
     numberlist += “Number “ + counter + “<br>”;
     counter -= 10;
}
document.write(numberlist);
</script> <body> … </body>
</html>

                              Keval Nagaria        111
“do … while” statement
    do {
           statements;
           counter increment/decrement;
     } while (termination condition)

 The do/while loop always executes
 statements in the loop in the first iteration of
 the loop.
 The termination condition is placed at the
 bottom of the loop.

                    Keval Nagaria                   112
Functions
 A function is a block of organized reusable
 code (a set of statements) for performing a
 single or related action.
 Begins with keyword “function” and the
 function name and “( … )”
 Inside the parentheses
   We can pass parameters to the function
   E.g. function myfuc(arg1, arg2) {…}
   Built-in and user-defined functions




                     Keval Nagaria             113
Built-In Functions
 Functions provided by the language and you
 cannot change them to suit your needs.
 Some of the built-in functions in JavaScript are
 shown here:
     eval - eval(expr)
          eval evaluates the expression or statements
     isFinite
          Determines if a number is finite
     isNaN
          Determines whether a value is “Not a Number”
     parseInt
          Converts string literals to integers, no number  NaN.
     parseFloat
          Finds a floating-point value at the beginning of a string.
                                Keval Nagaria                           114
User-Defined Functions
  For some functionality, you cannot achieve
  by only using the built-in functions.
  You can define a function as follows

function <function_name> (parameters)
{
    // code segments;
}


                   Keval Nagaria               115
Function Declarations
•   Declaration Syntax
       Functions are declared using the function reserved
        word
       The return value is not declared, nor are the types of
        the arguments
       Examples:

         function square(x) { return(x * x); }

         function factorial(n) {
             if (n <= 0) {
               return(1);
             } else {
               return(n * factorial(n - 1));
             }
         }
                             Keval Nagaria                       116
Events
 Events are the actions that occur as a result
 of browser activities or user interactions
 with the web pages.
   Such as the user performs an action (mouse
    click or enters data)
   We can validate the data entered by a user in a
    web form
   Communicate with Java applets and browser
    plug-ins



                      Keval Nagaria                   117
Event Categories
 Keyboard and mouse events
     Capturing a mouse event is simple
 Load events
     The page first appears on the screen: “Loads”, leaves:
      “Unloads”, …
 Form-related events
     onFocus() refers to placing the cursor into the text input
      in the form.
 Others
     Errors, window resizing.



                           Keval Nagaria                           118
 Events defined by JavaScript
HTML elements   HTML tags        JavaScript defined events   Description

Link            <a>              click                       Mouse is clicked on a link
                                 dblClick                    Mouse is double-clicked on
                                 mouseDown                   a link
                                 mouseUp                     Mouse button is pressed
                                 mouseOver                   Mouse button is released
                                                             Mouse is moved over a link
Image           <img>            load                        Image is loaded into a
                                 abort                       browser
                                 error                       Image loading is abandoned
                                                             An error occurs during the
                                                             image loading
Area            <area>           mouseOver                   The mouse is moved over
                                 mouseOut                    an image map area
                                 dblClick                    The mouse is moved from
                                                             image map to outside
                                                             The mouse is double-
                                                             clicked on an image map
Form            <form>           submit                      The user submits a form
                                 Reset                       The user refreshes a form
…               …                …                           …



                            Keval Nagaria                                                 119
Event Handlers
 When an event occurs, a code segment is
 executed in response to a specific event is
 called “event handler”.
 Event handler names are quite similar to the
 name of events they handle.
 E.g the event handler for the “click” event is
 “onClick”.

 <HTMLtag eventhandler=“JavaScript Code”>




                   Keval Nagaria                  120
Event Handlers
Event Handlers         Triggered when
onChange               The value of the text field, textarea,
                       or a drop down list is modified
onClick                A link, an image or a form element
                       is clicked once
onDblClick             The element is double-clicked
onMouseDown            The user presses the mouse button
onLoad                 A document or an image is loaded
onSubmit               A user submits a form
onReset                The form is reset
onUnLoad               The user closes a document or a
                       frame
onResize               A form is resized by the user

                 Keval Nagaria                                  121
onClick event Handler
<html>
<head>
<title>onClick Event Handler Example</title>
<script language=“JavaScript”>
function warnUser(){ return confirm(“INE2720 students?”); }
</script>
</head>
<body>
<a href=“reference.html”, onClick=“return
   warnUser();”>INE2720 Students access only</a>
</body>
</html>




                         Keval Nagaria                        122
onLoad event Handler
<html>
<head>
<title>onLoad and onUnload Event Handler
   Example</title>
</head>
<body onLoad=“alert(„Welcome User‟);”
onUnload=“alert(„Thanks for visiting the page‟);”>
Load and UnLoad event test.
</body>
</html>



                       Keval Nagaria                 123
User Events, Form Example
<html><head>
  <title>Simple JavaScript Button</title>
<script language=“JavaScript"><!--
function dontClick() {
   alert("I told you not to click!");
}
// --></script>
</head>

<body>
<h1>Simple JavaScript Button</h1>
<form>
 <input type=“button"
      value="Don't Click Me"
      onClick="dontClick()">
</form>
</body></html>


                                       Keval Nagaria   124
onMouseOver and onMouseOut Event Handlers

<html>
<head>
<title>onMouseOver and onMouseOut event handler</title>
</head>
<body>
<a href=“link.html”
onMouseOver = “status = „Now mouse is over the link‟; “
onMouseOut = “status = „Mouse has moved out‟;”>
A Link Page
</a>
</body>
</html>



                          Keval Nagaria                   125
Understanding JavaScript Objects
 One of the most important features of JavaScript, enables
 modular programs.
 Objects are based on Classes, variables, functions,
 statements are contained in a structure called class.

 Class
                         varA                   varB

                         varC                   varD


         FunctionA (…)                    FunctionB (…)


         FunctionC (…)                    FunctionD (…)



                                Keval Nagaria                126
Class and Object
 You can instantiate an object from a class by using
 the constructor function.
 JavaScript is said to be an Object-based
 programming language.
 What is property?
     A variable belongs to the object.
 What is method?
     It is a function belongs to the object.
     Function-Valued Properties




                            Keval Nagaria              127
Creating Instances of Objects
 You can use the “new” operator to create instances
 of objects of a particular class or object type.
     Variable = new objectType(parameters)
 This objectType() is called constructor.
 E.g. Date is a predefined object type.
     Assign the current date and time to objA
          objA = new Date()
     Assign another date and time to objB
          objB = new Date(99,23,5)  23 May, 99




                            Keval Nagaria             128
Objects and Classes
•   Fields Can Be Added On-the-Fly
       Adding a new property (field) is a simple
        matter of assigning a value to one
       If the field doesn‟t already exist when you try
        to assign to it, JavaScript will create it
        automatically.
       For instance:

    var test = new Object();
    test.field1 = "Value 1"; // Create field1 property
    test.field2 = 7;         // Create field2 property



                         Keval Nagaria                    129
Objects and Classes – Literal Notation
•   You Can Use Literal Notation
        You can create objects using a shorthand “literal”
         notation of the form

        { field1:val1, field2:val2, ... , fieldN:valN }

        For example, the following gives equivalent values to
         object1 and object2
         var object1 = new Object();
         var object2 = new Object();
         object1.x = 3;
         object1.y = 4;
         object1.z = 5;
         object2 = { x:3, y:4, z:5 };


                               Keval Nagaria                     130
Objects and Classes - Constructor
•       A “Constructor” is Just a Function that Assigns to “this”
    •      JavaScript does not have an exact equivalent to Java‟s class
           definition
    •      The closest you get is when you define a function that assigns
           values to properties in the this reference
    •      Calling this function using new binds this to a new Object
    •      For example, following is a simple constructor for a Ship class

          function Ship(x, y, speed, direction) {
                 this.x = x;
                 this.y = y;
                 this.speed = speed;
                 this.direction = direction;
          }


                                 Keval Nagaria                               131
Class Methods, Example
 function degreesToRadians(degrees) {
   return(degrees * Math.PI / 180.0);
 }

  function move() {
    var angle = degreesToRadians(this.direction);
    this.x = this.x + this.speed * Math.cos(angle);
    this.y = this.y + this.speed * Math.sin(angle);
  }

  function Ship(x, y, speed, direction) {
    this.x = x;
    this.y = y;
    this.speed = speed;
    this.direction = direction;
    this.move = move;
  }



                               Keval Nagaria          132
Build-In JavaScript Objects
Object              Description
Array               Creates new array objects
Boolean             Creates new Boolean objects
Date                Retrieves and manipulates dates and
                    times
Error               Returns run-time error information
Function            Creates new function objects
Math                Contains methods and properties for
                    performing mathematical
                    calculations
Number              Contains methods and properties for
                    manipulating numbers.
String              Contains methods and properties for
                    manipulating text strings
              Keval Nagaria                               133
Keval Nagaria   134
Keval Nagaria   135

				
DOCUMENT INFO
Shared By:
Tags:
Stats:
views:118
posted:8/16/2012
language:Latin
pages:135
Description: GTU MCA PPT