High Level Language Features - PowerPoint PPT Presentation

1 / 45
About This Presentation
Title:

High Level Language Features

Description:

Cross-Browser DHTML includes: shared support for Cascading Style Sheets, level 1 (CSS1) ... Anything which is browser or platform dependent is not cross-browser DHTML. ... – PowerPoint PPT presentation

Number of Views:49
Avg rating:3.0/5.0
Slides: 46
Provided by: Preu
Category:

less

Transcript and Presenter's Notes

Title: High Level Language Features


1
High Level Language Features
  • Introduction to JavaScript

Programming languages should be designed not by
piling feature on top of feature, but by removing
the weaknesses and restrictions that make
additional features appear necessary. The
Revised5 Report on the Algorithmic Language
Scheme
2
Variable Declaration Initialization
  • To avoid error from uninitialized data or
    unmatched data type, most HLL expect the variable
    to be declared and initialized before use.
  • Example
  • In C
  • int num
  • int x 0
  • char c a

In JavaScript var num var x 0 var c a
3
Arithmetic Assignment
  • Arithmetic assignment is an abbreviated form of
    an arithmetic expression such as follows
  • int c 0
  • c c3
  • Now, c c 3 can also be written as
  • c 3
  • It is of the form
  • variable operator expression
  • How would we write c c 3?

4
Conditional operator ?
  • Closely related to if/else structure
  • Most HLL compilers provide this operator
  • It is a ternary operator (with three operands)
  • The operands, together with the conditional
    operator, form a conditional expression
  • Of the form
  • (True/False condition ?
  • Action if true
  • Action if false)
  • print (grade gt 60 ? Passed Failed)
  • Will print Passed if grade is input as 75.

5
? Conditional Operator Example
  • In JavaScript
  • var greeting
  • hello ((name ! null) ? name there)
  • Is the same as
  • greeting hello
  • if(name ! null)
  • greeting name
  • else
  • greeting there

6
Unary Increment Decrement Operators
  • If a variable is incremented (or, decremented) by
    1, the increment (decrement) operator (--) can
    be used
  • c c 1 c c-1
  • c 1 c - 1
  • c c--
  • All mean the same thing in this context of
    incrementing (decrementing) by 1.
  • This is also known as post-increment
    (post-decrement) operator because the variable is
    incremented (decremented) after the current value
    of the variable is used in the expression in
    which it appears.

7
Pre increment and post increment
  • Preincrement a
  • Increment the current value of a and then use the
    new value
  • Postincrement a
  • Use the current value of a and then increment
  • Predecrement --b
  • decrease b by 1 and then use the new value
  • Postdecrement b--
  • use the current value of b and then decrease it
    by 1

8
Code Snippet what is the output?
  • var i0
  • var j, k
  • while (i lt 5)
  • document.write(i)
  • j i
  • document.write(j)
  • k --i
  • document.write(k)
  • Output is
  • i 1, j i is 1, k --i is 1
  • i 2, j i is 2, k --i is 2
  • i 3, j i is 3, k --i is 3
  • i 4, j i is 4, k --i is 4
  • i 5, j i is 5, k --i is 5
  • i 6, j i is 6, k --i is 6

9
Code Snippet what is the output?
  • var i0
  • var j, k
  • while (i lt 5)
  • document.write(i)
  • document.write(i)
  • document.write(--i)
  • Output is
  • i 0, i 2, --i 1i 1, i 3,
    --i 2i 2, i 4, --i 3i 3, i
    5, --i 4i 4, i 6, --i 5i 5, i
    7, --i 6

10
Using increment or decrement operators
  • Can only be used with a simple variable name, not
    with an expression
  • Example writing something like
  • (xy)
  • is a syntax error in most HLL compilers.
  • Preincrement and predecrement operate slightly
    faster than postincrement and postdecrement in
    most compilers like C,C.

11
Operators, Precedence,Associativity, and Type
12
Keyword function in JS
  • The function statement defines a function in JS
  • function functionName(arg1, arg2, , argn)
  • statements
  • The body of the function can contain any number
    of valid JS statements within in the curly
    brackets
  • Statements are not executed when the function is
    defined, but only when they are invoked via a
    function call
  • A return statement allows for returning values
    from the function to the caller

13
Some simple JS function definitions
  • function welcome()
  • alert(Welcome to my home page!)
  • function printMsg(msg)
  • document.write(msg, ltbrgt)
  • function hypotenuse(x, y)
  • return Math.sqrt(xx yy)

14
Switch The multi-way selection
  • We can use multi-way nested if statements for
    conditional branching
  • Problem If all of the branches depend on the
    value of a single variable, there is wasteful
    repeated checking
  • Solution Use switch statement
  • switch (expression)
  • case statements
  • Uses break statement to exit the switch (or a
    loop) structure.

15
Switch example in JS
  • function examine_n(n)
  • switch(n)
  • case 1 document.write(one)
  • break
  • case 2 document.write(two)
  • break
  • case 3 document.write(three)
  • break
  • case 4 document.write(four)
  • break
  • default document.write(bad input)
  • procedure examine_n(n)
  • if(n 1)
  • write(one)
  • else if (n 2)
  • write(two)
  • else if (n 3)
  • write(three)
  • else if (n 4)
  • write(four)
  • else
  • write(bad input)

16
for and while loops
  • for (initialize test increment)
  • statement
  • Is equivalent to
  • initialize
  • while(test)
  • statement
  • increment

17
for and while loops in JS
  • var count
  • for (count 1 count lt 10 count)
  • document.write(count ltBRgt)
  • Is the same as
  • var count 1
  • while (count lt 10)
  • document.write(count ltBRgt)
  • count

18
The Web Browser Programming Environment
  • The programming environment provided the web
    browser has three important features
  • The Window object that serves as the global
    object and global execution context for
    client-side JS code
  • The client-side object hierarchy
  • The event-driven programming
  • JS is not the only language that can be embedded
    in this web programming environment (ex.,
    VBScript, Tcl/Tk, PHP).
  • Lets try to understand each of the three
    features

19
1. The Window object
  • This object represents a web browser window or
    frame within that window
  • Each window object defines a unique execution
    context for the client-side JS code
  • To that effect, each window object has certain
    properties and methods associated with it
  • Example of window object properties status,
    defaultStatus, location, name, self, top,
    history, frames
  • Example of window object methods close(),
    focus(), blur(), alert(), confirm(), prompt()
  • See slide 29 for JS Object Hierarchy chart

20
2. Client-side JS in Web Browser Environment
  • The client-side JS where the client is
    usually understood to be a web client like a
    browser is
  • When a JS interpreter is embedded in a web
    browser so that
  • The scripting ability of JS interpreter along
    with the document object model defined by a web
    browser combine in a synergistic way so that
  • The result is rather dynamic meaning, it
    enables executable content to be distributed over
    the web leading to the evolution of Dynamic
    HTML or DHTML.
  • Aside JS was originally called LiveScript

21
3. The Event-Driven Programming Model
  • Recall that in the old days, computer programs
    often ran in the batch mode viz., it read in a
    batch of data and did some computations and then
    dumped out the results
  • gt virtually no interaction between user and
    machine while the computation is going on.
  • Then, with time-share mode and text-based
    terminals, limited interactivity became possible
  • gt program could ask for user input and the user
    could type in data that can then be used for
    continuing the computation

22
3. The Event-Driven Programming Model
  • Nowadays, with graphical displays and pointing
    devices like mice, programs are generally
    event-driven viz.,
  • user input can be via keystroke or mouse pointer
    called an event
  • program responds to such an event via what are
    known as event-handlers
  • JS has Objects have Properties (P), Methods (M)
    and Event Handlers (E) pre-defined and
    conveniently packaged for extending HTML
    capabilities

23
Server-side JS in Web Environment
  • Server-side JS core JS is extended for use in
    web servers (example LiveWire by Netscape)
  • Used as an alternative to CGI Scripts (Common
    Gateway Interface)
  • When a web client requests a document that has
    server-side JS content, the web server executes
    the script and serves up the result to the
    client
  • where the resulting document may be static or
    dynamic
  • And as speed is crucial for server-side JS, it is
    usually precompiled and stored in binary form so
    that
  • it can be efficiently interpreted and sent to
    the client should a request come in.

24
Embedded JS
  • JS is a general purpose programming (scripting)
    language
  • Its use is not restricted to web servers and web
    browsers (web clients)
  • Aside Netscape made the source code for JS
    interpreter freely available, along with source
    code to its web browser (www.mozilla.org)

25
The Document Object Model (DOM)
  • DOM is an evolving standard that specifies, among
    other things, how a scripting language like JS
    can access and manipulate the detailed structure
    of an HTML or XML document.
  • Refer W3C site for details http//www.w3.org/DOM/
  • DOM Level 0 has been the standard for a while,
    then IE4.0 implemented the emerging standard of
    DOM Level 1.
  • Working group of W3C has now come up with DOM
    Level 3, following DOM Level 2
  • The window object, as we saw earlier, is the
    central object in client-side JS
  • Every window object has a document property that
    refers to a document object that represents the
    (typically HTML) document.

26
JS-compatible browsers
  • There are currently many clients/browsers that
    support JavaScript, including
  • Netscape Navigator 2.0x,
  • Netscape Navigator 3.0x,
  • Netscape Navigator 4.0x,
  • Microsoft Internet Explorer 3.0x, and
  • Microsoft Internet Explorer 4.0.
  • When you write a script and embed it in your
    site, it will be interpreted by different
    interpreters on the viewers browser with unequal
    capabilities and features because
  • Unlike server-side scripts which you have full
    control over their interpretation, client-side
    scripts are executed by the user's browser.

27
JS-compatible browsers
  • Each browser supports different JavaScript
    features
  • And, each "feature" its own bugs.
  • Some bugs are platform-specific, while others are
    browser-specific.
  • Some objects are supported by Navigator 3.0x,
    4.0x, and Internet Explorer 4.0, but are not
    supported by Navigator 2.0x and Internet Explorer
    3.0x.
  • There are quite a few ways to deal with these
    compatibility issues including finding out which
    browser the users client browser is running and
    account for incompatibilities in your script.
  • Check out http//hotwired.lycos.com/webmonkey/refe
    rence/browser_chart/ for a quick summary of
    browsers and compatibility

28
Cross-browser compatibility
  • Netscape and Microsoft each had their own
    definition of Dynamic HTML in their browsers. The
    W3C DOM level 1 (supported in Mozilla and
    Netscape 6) and W3C DOM level 2 (partially
    supported in Mozilla and Netscape 6) provide for
    the first time an industry standard way of
    writing Dynamic HTML.
  • Cross-Browser DHTML includes
  • shared support for Cascading Style Sheets, level
    1 (CSS1)
  • shared support for Cascading Style Sheets
    Positioning (CSSP)
  • shared JavaScript support
  • Document Object Model functionality
  • event model functionality
  • downloadable font resources (also known as
    Dynamic Fonts)
  • full screen mode
  • Anything which is browser or platform dependent
    is not cross-browser DHTML.
  • To this effect, we will use HTML comment tags to
    avoid confusing non-JS compatible browsers

29
Everything in JS is an Object
  • The emphasis is on the thing i.e., if it is
    not an action or a description, then it is
    probably an object
  • Some commonly used JS objects (top-down) are
  • window
  • document
  • form
  • image
  • Of these objects, the first and central one
    inside the window object is the document object.
  • The document object has several properties and
    methods that help interaction with the user.
    Well study a few of them shortly.

30
JS Object Hierarchy
  • Objects are one of the fundamental data types in
    JS
  • Objects are pre-defined
  • Primitive data types hold one type of value,
    whereas Objects are a compound data type and
    therefore aggregate multiple data values into
    single units to store and retrieve them
    collectively by object name
  • In other words, an Object is a collection of
    properties and methods, each of which has a name
    and value associated.

31
JS Object Hierarchy
32
The Dot Operator Dot Syntax
  • Used to access object properties and methods
  • Written as
  • objectName.propertyName
  • objectName.methodName()
  • As JS Objects are hierarchical, we can traverse
    down the hierarchy from top to bottom, accessing
    the properties or methods via the dot operator
    along the path
  • Example
  • document.write() is a method of the document
    object
  • document.forms0.selector.selectedIndex is the
    selectedIndex property of the selector object of
    the first form (from form0 array) object of the
    document object

33
The document object
  • document.bgColor
  • corresponds to the BGCOLOR property of the
    ltBODYgt tag in HTML
  • document.write()
  • accesses the write method of the document object
    and allows writing output or displaying formatted
    HTML output on the current document
  • and so on

Refer http//spot.pcc.edu/spreuitt/CS160/images/J
SObjChart.jpg for a detailed picture of the JS
object hierarchy
34
Communicating with user via dialog boxes
  • Dialog boxes allow for displaying and receiving
    information, thus providing a simple way to
    interact with the user. There are three ways in
    which JS lets you do this
  • alert() has an OK button to help user clear the
    alert dialog box
  • alert(message)
  • confirm() has an OK and Cancel button, or Yes
    and No in Macs. This method returns the users
    answer to the script in the form of True or False
  • document.write(confirm(message))
  • prompt() uses two arguments, and has two buttons
    OK and Cancel just like confirm(), but, returns
    the text entered by the user, or null, if nothing
    is entered by the user.
  • document.write(promptm(message, ))
  • All dialog boxes, like buttons on a web page, use
    standard parts of users OS. So, for example, an
    alert box would look different on a Macintosh
    than on a machine running Windows.

35
Where should JS be embedded?
  • JS code can be hidden away in the ltHEADgt lt/HEADgt
    section of an HTML page as we will see in some
    examples
  • JS functions so defined in the ltHEADgt lt/HEADgt
    section can be invoked from within the ltBODYgt
    part of the HTML document based on some event
    that triggers it, as we will see in some examples
  • JS can be embedded in HTML ltBODYgt directly, in
    which case, you can define a function inside the
    ltBODYgt tag and have it displayed in the current
    document directly as seen in the next example

36
A simple JS program in web environment
  • ltHTMLgt
  • ltHEADgt ltTITLEgt JS FACTORIAL EXAMPLE lt/TITLEgt
  • lt/HEADgt
  • ltBODYgt
  • ltSCRIPT LANGUAGE JavaScriptgt
  • document.write(ltH2gtTable of factorialslt/H2gt)
  • for (i1, fact 1 i lt 10 i, fact i)
  • document.write(i ! fact)
  • document.write(ltBRgt)
  • lt/SCRIPTgt
  • lt/BODYgt
  • lt/HTMLgt
  • http//spot.pcc.edu/spreuitt/CS160/JSFolder/JSFac
    torial.html

37
Event Handlers JS and HTML ltFORMgt
  • JS can be executed when a particular event occurs
    in an HTML document like when a user clicks a
    button.
  • A simple example
  • ltHTMLgt
  • ltBODYgt
  • ltFORMgt
  • ltINPUT TYPEbutton
  • VALUEClick this button
  • onClickalert(You clicked the button)gt
  • lt/FORMgt
  • lt/BODYgt
  • lt/HTMLgt
  • http//spot.pcc.edu/spreuitt/CS160/JSFolder/JSBut
    tonClick.html

38
HTML FORM ELEMENTS
  • ltFORMgt element expands HTML capabilities by
    allowing for widgets
  • like buttons, checkboxes, radio buttons,
    pull-down selection lists, text fields and so on
  • that are useful for communicating with the user
    to get input or display some output.
  • ltFORMgt elements (there can be multiple forms in
    an HTML page) are placed in the ltBODYgt of an HTML
    document and enclose all sub-elements that appear
    as part of the form.

39
HTML ltFORMgt Elements
40
JS Form Objects, Properties, Methods and Event
Handlers
  • forms object in JS is a part of document
    object, meaning,
  • it is one step lower in the JS object hierarchy
    from the document object
  • forms is an array, meaning there can be more
    than one form in a document object
  • forms can also be accessed by their name
    attribute
  • Form Events
  • onSubmit
  • onReset
  • Form Properties
  • action
  • encoding
  • length
  • method
  • target
  • Forms Methods
  • submit()
  • reset()

41
Example of HTML FORM elements
  • ltHTMLgt
  • ltBODYgt
  • ltFORM nameExample1gt
  • ltINPUT TYPEbutton
  • VALUEClick this button
  • onClickalert(You clicked the first
    button)gt
  • ltINPUT TYPEbutton
  • VALUEor this button
  • onClickalert(You clicked the second
    button)gt
  • ltBRgtAre you having fun yet?
  • ltINPUT TYPEradio NAMEfun VALUEyesgt Yes
  • ltINPUT TYPEradio NAMEfun VALUEnogt NO!
  • ltINPUT TYPEradio NAMEfun VALUEmaybe
    CHECKEDgt Maybe
  • ltBRgtWhy are we doing this?
  • ltINPUT TYPEcheckbox NAMElearn CHECKEDgt To
    Learn
  • ltINPUT TYPEcheckbox NAMEhaveTogt Because I
    have to!

42
JS Primitive Data Types
  • JS allows three types of data
  • Strings
  • Numbers
  • Boolean
  • Everything is a string!
  • String is a collection of all kinds of characters
    that can be represented and so, can contain
    numbers, and Booleans
  • Making Numbers
  • Use a built-in functions to convert input string
    to numbers explicitly

43
JS Numbers from Strings
  • Even if the user enters a number in a text field
    of an HTML form, JS reads it as a string.
  • To do numerical operations on this, first convert
    it to a number using one of the three ways
  • Use eval() to convert the input string to numbers
  • Use parseInt() to convert the input string to
    integers
  • Use parseFloat() to convert the input string to
    decimal floating point

44
JS Numbers to Strings
  • JS automatically converts input numbers to
    strings,
  • however, you may want to do it explicitly in your
    code to display the number in a particular base
    system, say Hex, for HTML Hex color codes
  • Use the method toString(base)
  • Example
  • function convertNum(numStr, baseStr)
  • var numVal eval(numStr)
  • var baseVal eval(baseStr)
  • var result numVal.toString(baseVal)
  • document.write(result)
  • Note Base should be a number between 2 and 16
  • http//spot.pcc.edu/spreuitt/CS160/JSFolder/JStoS
    tring.html

45
Summary
  • There are lots of details (that we cannot go into
    due to lack of time) that make JS quite
    interesting
  • There are some good references and introduction
    on the web. Try not to get bogged down by
    complicated examples on these sites and please do
    not use any of the free codes available on the
    web it is plagiarism!!
  • Practice writing your own JS and youll soon see
    that you can do a lot of fun stuff
Write a Comment
User Comments (0)
About PowerShow.com