1 / 69

JavaScript

JavaScript. Overview. Overview. About Basics Objects DOM. About JavaScript. JavaScript is not Java, The original name for JavaScript was “LiveScript” The name was changed when Java became popular

clee
Télécharger la présentation

JavaScript

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JavaScript Overview

  2. Overview • About • Basics • Objects • DOM

  3. About JavaScript • JavaScript is not Java, • The original name for JavaScript was “LiveScript” • The name was changed when Java became popular • Now that Microsoft no longer likes Java, its name for their JavaScript dialect is “Active Script” • Statements in JavaScript resemble statements in Java, because both languages borrowed heavily from the C language • JavaScript should be fairly easy for Java programmers to learn • However, JavaScript is a complete, full-featured, complex language • JavaScript is seldom used to write complete “programs” • Instead, small bits of JavaScript are used to add functionality to HTML pages • JavaScript is often used in conjunction with HTML “forms” • JavaScript is reasonably platform-independent

  4. Javascript --- 2 kinds??? • JavaScript • Runs on client • NodeJS (not the topic of this lecture) • NEW • Runs on server

  5. JavaScript (client side) Allows Interactivity • Improve appearance • Especially graphics • Visual feedback • Site navigation • Perform calculations • Validation of input • Other technologies javascript.internet.com

  6. Why talk about JavaScript? • Very widely used, and growing • Web pages, AJAX, Web 2.0 • Increasing number of web-related applications • Some interesting and unusual features • First-class functions - interesting • Objects without classes - slightly unusual • Powerful modification capabilities - very unusual • Add new method to object, redefine prototype, access caller … • Many security, correctness issues • Not statically typed – type of variable may change … • Difficult to predict program properties in advance

  7. Using JavaScript in a browser • JavaScript code is included within <script> tags: • <script type="text/javascript"> document.write("<h1>Hello World!</h1>") ;</script> • Notes: • The type attribute is to allow you to use other scripting languages (but JavaScript is the default) • This simple code does the same thing as just putting <h1>HelloWorld!</h1>in the same place in the HTML document • The semicolon at the end of the JavaScript statement is optional • You need semicolons if you put two or more statements on the same line • It’s probably a good idea to keep using semicolons

  8. JavaScript isn’t always available • Some old browsers do not recognize script tags • These browsers will ignore the script tags but will display the included JavaScript • To get old browsers to ignore the whole thing, use:<script type="text/javascript"> <!--document.write("Hello World!") //--></script> • The <!-- introduces an HTML comment • To get JavaScript to ignore the HTML close comment, -->, the//starts a JavaScript comment, which extends to the end of the line • Some users turn off JavaScript • Use the <noscript>message</noscript> to display a message in place of whatever the JavaScript would put there

  9. Where to put JavaScript • JavaScript can be put in the<head>or in the <body>of an HTML document • JavaScript functions should be defined in the<head> • This ensures that the function is loaded before it is needed • JavaScript in the<body>will be executed as the page loads • JavaScript can be put in a separate.jsfile • <script src="myJavaScriptFile.js"></script> • Put this HTML wherever you would put the actual JavaScript code • An external.jsfile lets you use the same JavaScript on multiple HTML pages • The external.jsfile cannot itself contain a<script>tag • JavaScript can be put in an HTML form object, such as a button • This JavaScript will be executed when the form object is used

  10. welcome.html(1 of 1) HTML comment tags will result in skipping of the script by those browsers that do not support scripting

  11. welcome2.html(1 of 1) Escape character in combination with quotation mark: \” will result in insertion of a quotation mark in the string that is actually written by JavaScript

  12. welcome3.html1 of 1 New line of the html document in a browser is determined by an html <br /> element

  13. JavaScript • Variables are not typed ---you simply use them –no need to declare type show_info = new Boolean(true);         Year = "2002"; var Name = "Butch";     //instance variable var Age = 6;     //instance variable .......... Age ="Six Years"; //this is legal to change ......... • Instance Variables: • only accessible in the current function (or if not inside a function, the current script) • use the special keyword: var • Variables not declared as instance variables (preceeded by var), are accessible potentially anywhere

  14. Literals --- data types • JavaScript has three “primitive” types: number, string, and boolean • Everything else is an object • Numbers are always stored as floating-point values • Hexadecimal numbers begin with 0x • Some platforms treat 0123 as octal, others treat it as decimal • Since you can’t be sure, avoid octal altogether! • Strings may be enclosed in single quotes or double quotes • Strings can contains \n (newline), \" (double quote), etc. • Booleans are either true or false • 0,"0", empty strings,undefined,null, andNaNarefalse, other values are true

  15. Variables • Variables names must begin with a letter or underscore • names are case-sensitive • Variables are untyped (they can hold values of any type) • var is optional (but it’s good style to use it) • Variables declared within a function are local to that function (accessible only within that function) • Variables declared outside a function are global (accessible from anywhere on the page)

  16. Operators, I • Because most JavaScript syntax is borrowed from C (and is therefore just like Java), we won’t spend much time on it • Arithmetic operators (all numbers are floating-point):+ - * / % ++ -- • Comparison operators: < <= == != >= > • Logical operators: && || ! (&&and ||are short-circuit operators) • Bitwise operators: & | ^ ~ << >> >>> • Assignment operators:+= -= *= /= %= <<= >>= >>>= &= ^= |=

  17. Operators, II • String operator:+ • The conditional operator:condition ? value_if_true : value_if_false • Special equality tests: • ==and!=try to convert their operands to the same type before performing the test • ===and!==consider their operands unequal if they are of different types • Additional operators (to be discussed):new typeof void delete

  18. Operators Always use parentheses to ensure desired order of evaluation:(a + b) / 6

  19. Comments • Comments are as in C or Java: • Between//and the end of the line • Between/*and*/ • Java’s javadoc comments,/** ... */, are treated just the same as/* ... */comments; they have no special meaning in JavaScript

  20. Example: simple calculation <html> … <p> … </p> <script> var num1, num2, sum num1 = prompt("Enter first number") num2 = prompt("Enter second number") sum = parseInt(num1) + parseInt(num2) alert("Sum = " + sum) </script> … </html>

  21. Statements, I • Most JavaScript statements are also borrowed from C • Assignment: greeting = "Hello, " + name; • Compound statement:{ statement; ...; statement } • If statements:if (condition) statement; if (condition) statement; else statement; • Familiar loop statements:while (condition) statement; do statementwhile (condition); for (initialization; condition;increment) statement;

  22. Statements, II • The switch statement: switch (expression) { case label :statement; break; case label :statement; break; ... default : statement; } • Other familiar statements: • break; • continue; • The empty statement, as in;;or{ }

  23. JavaScript is not Java • By now you should have realized that you already know a great deal of JavaScript • So far we have talked about things that are the same as in Java • JavaScript has some features that resemble features in Java: • JavaScript has Objects and primitive data types • JavaScript has qualified names; for example, document.write("Hello World"); • JavaScript has Events and event handlers • Exception handling in JavaScript is almost the same as in Java • JavaScript has some features unlike anything in Java: • Variable names are untyped: the type of a variable depends on the value it is currently holding • Objects and arrays are defined in quite a different way • JavaScript has with statements and a new kind of for statement

  24. Array literals • You don’t declare the types of variables in JavaScript • JavaScript has array literals, written with brackets and commas • Example: color = ["red", "yellow", "green", "blue"]; • Arrays are zero-based:color[0]is"red" • If you put two commas in a row, the array has an “empty” element in that location • Example:color = ["red", , , "green", "blue"]; • colorhas 5 elements • However, a single comma at the end is ignored • Example: color = ["red", , , "green", "blue”,]; still has 5 elements

  25. Arrays created Simply define a variable to be an array and call the built-in JavaScript class Array's constructor as follows:

  26. Four ways to create an array • You can use an array literal:var colors = ["red", "green", "blue"]; • You can use new Array()to create an empty array: • var colors = new Array(); • You can add elements to the array later:colors[0] = "red"; colors[2] = "blue"; colors[1]="green"; • You can usenew Array(n)with a single numeric argument to create an array of that size • var colors = new Array(3); • You can usenew Array(…)with two or more arguments to create an array containing those values: • var colors = new Array("red","green", "blue");

  27. The length of an array • IfmyArray is an array, its length is given by myArray.length • Array length can be changed by assignment beyond the current length • Example:var myArray = new Array(5); myArray[10] = 3; • Arrays are sparse, that is, space is only allocated for elements that have been assigned a value • Example: myArray[50000] = 3;is perfectly OK • But indices must be between 0 and 232-1 • As in C and Java, there are no two-dimensional arrays; but you can have an array of arrays: myArray[5][3]

  28. Arrays and objects • Arrays are objects • car = { myCar: "Saturn", 7: "Mazda" } • car[7]is the same ascar.7 • car.myCaris the same ascar["myCar"] • If you know the name of a property, you can use dot notation: car.myCar • If you don’t know the name of a property, but you have it in a variable (or can compute it), you must use array notation: car["my" + "Car"]

  29. Array functions • If myArray is an array, • myArray.sort()sorts the array alphabetically • myArray.sort(function(a, b) { return a - b; })sorts numerically • myArray.reverse()reverses the array elements • myArray.push(…)adds any number of new elements to the end of the array, and increases the array’s length • myArray.pop()removes and returns the last element of the array, and decrements the array’s length • myArray.toString() returns a string containing the values of the array elements, separated by commas

  30. The for…instatement • You can loop through all the properties of an object with for (variableinobject)statement; • Example: for (var prop in course) { document.write(prop + ": " + course[prop]); } • Possible output: teacher: Dr. Dave number: CIT597 • The properties are accessed in an undefined order • If you add or delete properties of the object within the loop, it is undefined whether the loop will visit those properties • Arrays are objects; applied to an array, for…in will visit the “properties” 0, 1, 2, … • Notice that course["teacher"]is equivalent to course.teacher • You must use brackets if the property name is in a variable

  31. The with statement • with (object) statement;uses the object as the default prefix for variables in the statement • For example, the following are equivalent: • with (document.myForm) { result.value = compute(myInput.value) ;} • document.myForm.result.value = compute(document.myForm.myInput.value); • One of my books hints at mysterious problems resulting from the use of with, and recommends against ever using it

  32. Functions • Functions should be defined in the<head>of an HTML page, to ensure that they are loaded first • The syntax for defining a function is:function name(arg1, …, argN) { statements } • The function may contain return value; statements • Any variables declared within the function are local to it • The syntax for calling a function is justname(arg1, …, argN) • Simple parameters are passed by value, objects are passed by reference

  33. More about functions • Declarations can appear in function body • Local variables, “inner” functions • Parameter passing • Basic types passed by value, objects by reference • Call can supply any number of arguments • functionname.length : # of arguments in definition • functionname.arguments.length : # args in call • “Anonymous” functions (expressions for functions) • (function (x,y) {return x+y}) (2,3);

  34. Function Examples • Anonymous functions make great callbacks setTimeout(function() { alert("done"); }, 10000) • Variable number of arguments function sumAll() { var total=0; for (var i=0; i< sumAll.arguments.length; i++) total+=sumAll.arguments[i]; return(total); } sumAll(3,5,3,5,3,2,6)

  35. Exception handling, I • Exception handling in JavaScript is almost the same as in Java • throwexpression creates and throws an exception • The expression is the value of the exception, and can be of any type (often, it's a literal String) • try {statements to try} catch (e) { // Notice: no type declaration foreexception handling statements} finally { // optional, as usualcode that is always executed} • With this form, there is only onecatch clause

  36. Exception handling, II • try {statements to try} catch (e if test1) { exception handling for the case that test1 is true} catch (e if test2) { exception handling for when test1 is false and test2 is true} catch (e) { exception handling for when both test1and test2 are false} finally { // optional, as usualcode that is always executed} • Typically, the test would be something likee == "InvalidNameException"

  37. Regular expressions • A regular expression can be written in either of two ways: • Within slashes, such asre = /ab+c/ • With a constructor, such as re = new RegExp("ab+c") • Regular expressions are almost the same as in Perl or Java (only a few unusual features are missing) • string.match(regexp) searches stringfor an occurrence of regexp • It returns nullif nothing is found • If regexphas the g (global search) flag set, match returns an array of matched substrings • If gis not set, match returns an array whose 0th element is the matched text, extra elements are the parenthesized subexpressions, and the index property is the start position of the matched substring

  38. Objects in JavaScript

  39. JavaScript: Object-Based Language • There are three object categories in JavaScript: Native Objects, Host Objects, and User-Defined Objects. • Native objects: defined by JavaScript. • String, Number, Array, Image, Date, Math, etc. • Host objects : supplied and always available to JavaScript by the browser environment. • window, document, forms, etc. • User-defined objects : defined by the author/programmer

  40. User defined Classes/Objects How to create your own

  41. Object literals • You don’t declare the types of variables in JavaScript • JavaScript has object literals, written with this syntax: • { name1 : value1 , ... , nameN : valueN } • Example (from Netscape’s documentation): • car = {myCar: "Saturn", 7: "Mazda", getCar: CarTypes("Honda"), special: Sales} • The fields are myCar, getCar, 7(this is a legal field name) , and special • "Saturn" and "Mazda" are Strings • CarTypesis a function call • Sales is a variable you defined earlier • Example use: document.write("I own a " + car.myCar);

  42. Three ways to create an object • You can use an object literal: • var course = { number: "CIT597", teacher: "Dr. Dave" } • You can use new to create a “blank” object, and add fields to it later: • var course = new Object();course.number = "CIT597";course.teacher = "Dr. Dave"; • You can write and use a constructor: • function Course(n, t) { // best placed in <head> this.number = n; // keyword "this" is required, not optional this.teacher = t;} • var course = new Course("CIT597", "Dr. Dave");

  43. BOM, DOM and more “Host objects”

  44. Browser Object Model • The BOM defines the components and hierarchy of the collection of objects that define the browser window. • For the most part, we will only be working with the following components of the BOM. • window object • location object • history object • document object • navigator object • screen object

  45. Window object Navigator object Location object History object Document object Screen object Window Object • Top level in the BOM • Allows access to properties and method of: • display window • browser itself • methods thing such as error message and alert boxes • status bar

  46. Document Object • Top of the Document Object Model (DOM). • This is probably the one you’ll use most. • Allows access to elements of the displayed document such as images and form inputs. • The root that leads to the arrays of the document: forms[ ] array, links[ ] array, and images[ ] array. • Least compliance to standard here – Netscape 6, Opera 6, and Mozilla 1.0 are the best.

  47. Navigator Object • Provides access to information and methods regarding the client’s browser and operating system. • Commonly used to determine client’s browser capabilities so page can be modified real time for best viewing. • Example: A script may check the browser type in order to modify CSS styles.

  48. History Object • Provides access to the pages the client has visited during the current browser session. • Methods such as back() and forward() can be used to move through the history. • Can also be used to jump to any point in the history. • As with any browser history, it only allows for a single path.

  49. Other BOM Objects • Location Object – Provides access to and manipulation of the URL of the loaded page. • Screen Object – Provides access to information about the client’s display properties such as screen resolution and color depth. • More information can be found at: http://javascript.about.com/library/bltut22.htm http://www-128.ibm.com/developerworks/web/library/wa-jsdom/

  50. Document Object Model • Document is modeled as a tree. • DOM Changes based on page displayed. Example: <html><head> <title>My Page</title></head><body> <h1>My Page</h1> <p name=“bob” id=“bob”> Here’s the first paragraph.</p> <p name=“jim” id=“jim”> Here’s the second paragraph.</p></body></html> html head body title h1 p bob jim • Another example can be found at:http://oopweb.com/JavaScript/Documents/jsintro/Volume/part2/part2.htm

More Related