Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
4.4 JavaScript (JS) Deitel Ch. 7, 8, 9, 10 2 JavaScript & Java: Similarities • JS (JavaScript) is case-sensitive • Operators – – – – arithmetic: unary +, unary -, +, -, *, /, % bit-wise: ~ (unary), &, |, <<, >>, >>> logical: ! (unary), &&, || strings: + (concatenation) – compound assignment: • ++, --, • op= where op is one of the binary operators above, e.g., +=, -=, |=, &&=, – relational: ==, !=, <, >, <=, >= – conditional: op1 ? op2 : op3 (if op1 then op2 else op3) 3 JS & Java: Similarities (cont.) • Assignment with = • Syntax and semantic of control structures – – – – – – if if-else shift-case while do-while for • except for-in, that's different • Block {…} 4 JS & Java: Similarities (cont.+) • Syntax of identifers – e.g., index_1, theCamelNotation • Syntax of numeric and string constants: – e.g., -40, 3.14, 0.1E-7, 1.2e2, NaN, "a string", 0xFF00FF, 0x0a1b2c • Special characters: /n, /t, /f , /r, /", /', //, etc. • Special values: null, true, false • Subprogram calls: sub(p1,p2,…) • Array initialization – e.g.: var cars = ["Mini", "Miata"]; • Array indices begin with 0, end with length-1 • Array access: cars[0] 5 JS & Java: Similarities (cont.++) • • • • break statement continue statement return statement Subprograms can throw exceptions – exceptions are objects, can carry information – difference: subprograms don't declare what they throw • try-catch statement • Object instantiation: new Name(…) • All objects inherit method toString(…) 6 JS & Java: Differences • • • • • • • • Type-less variables vs. strongly typed Interpreted vs. hybrid Functional features vs. purely imperative Syntax: declarations, subprograms, classes, … Additional statements Different scope rules Only few standard objects vs. rich set of supporting classes (JDK) Very different Object-Oriented Facilities – – – – object-prototype vs. class concept no encapsulation different inheritance different syntax 7 Variables • Variables can be declared with var – mandatory for locals – optional, but recommended for globals • Global variables are assigned outside of functions • Typing is implicit – values have types, not variables – a variable can hold a value of any type – the expression decides the type • Type conversion errors are detected at run-time! 8 Types • Types: – "primitive": • undefined, null, boolean, number, string – function, object • Operator typeof – returns "undefined", "boolean", "number", "string", "function" or "object" – null or arrays are also "object"s 9 Values • Strings can be enclosed in ' – 'the "other" way' • Special value: undefined – var a = [1, , , 2]; // a[1],a[2] are undefined – undefined can be tested • if (value) {use(value)} else {alert("undefined value");} • In a condition – 0, "", null and undefined are interpreted as false – everything else is interpreted as true – Watch out: JS doesn't protect you against misuse of values in a condition! 10 Arrays • Array is an explicit object Array – e.g.: var cards = new Array(); – e.g.: var cards = new Array(12);//0..11 undefined – e.g.: var nos = new Array(1,2,3);//=[1,2,3] • Predefined property length • Assigning an element at index that didn't exist is ok – it extends the array • An associative array is not an Array object – indices can be strings – array notation used for accessing an object's properties • see later 11 Array methods • push(item) appends the item at index length • i.e., increments length • pop() removes and returns the last item – decrements length • shift() removes and returns the first item – decrements length and indices of all other items • slice(from,[to]) returns the subarray from..to-1 • concat(array) appends all items of array • splice(from,n,[it1,it2,…]) – replaces n items starting at from by items it1,it2,… • reverse(), sort(), toString() 12 Statements • Statements don't need to be separated by; – but they can – it's recommended – ; is needed for several statements on one line - don't do that! • for-in statements assigns consecutive indices – e.g.: for (var i in anArray) {alert(anArray[i]);} • with statement – allows using properties of an object without object prefix – e.g.: with (document) { write("<h1>Greetings</h1>"); //= document.write() write("<p>Hi there!</p>"); } 13 Subprograms • Syntax – function name (…) {…} • Anonymous functions – name = function (…) {…} – called the same way: name(…) • Function body is stored as text – it can be retrieved and modified! • Functions are data – they can be assigned to variables, stored in an array, etc. • A function is an object, can be defined that way – var sum = new Function("a","b","return a+b"); • A function can also define a "class" (see later) 14 Function Parameters • It's ok to call a function with fewer parameters – you can check for undefined values – also, arguments property holds an array of all parameter values • Parameter passing – by value • numbers, strings, true, false, null, undefined – by reference • objects • Return values are passed the same way 15 Built-in Functions: Dialogs • alert(message) – displays a modal dialog with message and OK button – often used while debugging • e.g., alert("variable=" + variable); – used to display multiple lines • e.g., alert("line 1\nline 2\nline3"); • confirm(message) – displays a modal dialog with message and with buttons OK and Cancel – returns true if the user clicked OK – returns false if the she clicked Cancel • prompt(message) – displays a modal dialog with message, input field and OK button – returns the text that the user typed into the input field 16 Built-in Functions (cont.) • parseInt(string) – attempts to convert the string into an integer number and return it – returns the integral part of a real number or NaN if string isn't a number • parseFloat(string) – attempts to convert the string into an floating point number and return it – returns NaN if string isn't a number • eval(expression) – interprets the expression as JavaScript code 17 JavaScript Pitfalls • JavaScript is "silent" – run-time errors stop script's execution – syntax errors may not matter if the code is not executed don't do that! • JS allows assignments within expressions – like Java – e.g. var x=++y – x=y--; //heck, what? – never use that! 18 Browser Pitfalls • IE just reports "runtime error" • Firefox error line numbers are off – check a line before or after • JS in IE is not the same as JS in Firefox is not the same as JS in Opera is not the same as … – in other words: var browsers = [Firefox,IE,Opera,Safari]; var text="You have to test and test because\n"; for (var i = 0; i < browsers.length; i++) { text+="JS in "+browsers[i]+" isn't the same as in\n"; } alert (text+"..."); 19 JS & Java • Facit: There are a lot of similarities But despite these similarities JS is very different from Java 20 More to Come • Object-Oriented JavaScript • JavaScript with DOM • Events with JavaScript