
4-advanced-javascript.ppt
- Количество слайдов: 31
Java. Script Language Fundamentals III
Browser support n n n Java. Script works on almost all browsers Internet Explorer uses JScript (referred to in menus as “Active Scripting”), which is Microsoft’s dialect of Java. Script Older browsers don’t support some of the newer features of Java. Script n n We will assume modern browser support Enabling and disabling Java. Script: n See http: //www. valleyvet. com/si_javascript_help. html 2
What you can’t do n To protect the visitor to your web pages, you can’t: n Read or write user files n n However, JScript on IE allows ASP scripting, which is how the very destructive JS. Gigger. A@mm worm spreads To turn off active scripting in Outlook Express, see http: //support. microsoft. com/support/kb/articles/Q 192/8/46. ASP n n Execute any other programs Connect to any other computer, except to download another HTML page or to send e-mail Determine what other sites the user has visited Open a very small (less than 100 px by 100 px) window or an offscreen window (except in IE) 3
Debugging n Mozilla/Netscape has much better debugging tools than IE n Mozilla n n Netscape 6: n n Type javascript: in the location bar and press Enter Internet Explorer: n n Select Communicator => Tools => Java. Script console Any Mozilla or Netscape: n n Select Tasks => Tools => Java. Script console Netscape 4: n n Select Tools => Web Development => Java. Script console Go to the Preferences. . . dialog and look for something like Web content => Show scripting error alerts After debugging, test your program in IE is the most popular browser 4
Numbers n n In Java. Script, all numbers are floating point Special predefined numbers: n n n Infinity, Number. POSITIVE_INFINITY -- the result of dividing a positive number by zero Number. NEGATIVE_INFINITY -- the result of dividing a negative number by zero Na. N, Number. Na. N (Not a Number) -- the result of dividing 0/0 n n Na. N is unequal to everything, even itself There is a global is. Na. N() function Number. MAX_VALUE -- the largest representable number Number. MIN_VALUE -- the smallest (closest to zero) representable number 5
Strings and characters n n In Java. Script, string is a primitive type Strings are surrounded by either single quotes or double quotes There is no “character” type Special characters are: b f n r t NUL backspace form feed newline carriage return horizontal tab v vertical tab ' single quote " double quote \ backslash x. DD Unicode hex DD x. DDDD Unicode hex DDDD 6
Some string methods n char. At(n) n n concat(string 1, . . . , string. N) n n Returns the position of the first character of substring in the recipient string, or -1 if not found index. Of(substring, start) n n Concatenates the string arguments to the recipient string index. Of(substring) n n Returns the nth character of a string Returns the position of the first character of substring in the given string that begins at or after position start, or -1 if not found last. Index. Of(substring), last. Index. Of(substring, start) n Like index. Of, but searching starts from the end of the recipient string 7
More string methods n match(regexp) n Returns an array containing the results, or null if no match is found n On a successful match: n n If g (global) is set, the array contains the matched substrings If g is not set: Array location 0 contains the matched text n Locations 1. . . contain text matched by parenthesized groups n The array index property gives the first matched position replace(regexp, replacement) n Returns a new string that has the matched substring replaced with the replacement search(regexp) n Returns the position of the first matched substring in the given string, or -1 if not found. n n n 8
boolean n n The boolean values are true and false When converted to a boolean, the following values are also false: n n n 0 "0" and '0' The empty string, '' or "" undefined null Na. N 9
undefined and null n n There are special values undefined and null undefined is the only value of its “type” n n This is the value of a variable that has been declared but not defined, or an object property that does not exist void is an operator that, applied to any value, returns the value undefined null is an “object” with no properties null and undefined are == but not === 10
Arrays n As in C and Java, there are no “true” multidimensional arrays n n n However, an array can contain arrays The syntax for array reference is as in C and Java Example: var var a = [ ["red", 255], ["green", 128] ]; b = a[1][0]; // b is now "green" c = a[1]; // c is now ["green", 128] d = c[1]; // d is now 128 11
Determining types n The unary operator typeof returns one of the following strings: "number", "string", "boolean", "object", "undefined", and "function" n n n typeof null is "object" If my. Array is an array, typeof my. Array is "object" To distinguish between different types of objects, n my. Object instanceof Constructor n n The Constructor should be an object that is a constructor function It is an error if the right-hand side is not an object at all my. Object. constructor == Constructor my. Object. to. String() == "Constructor. Name" 12
Wrappers and conversions n Java. Script has “wrapper” objects for when a primitive value must be treated as an object n n n var s = new String("Hello"); // s is now a String var n = new Number(5); // n is now a Number var b = new Boolean(true); // b is now a Boolean Because Java. Script does automatic conversions as needed, wrapper objects are hardly ever needed Java. Script has no “casts, ” but conversions can be forced n n var s = x + ""; // s is now a string var n = x + 0; // n is now a number var b = !!x; // b is now a boolean Because Java. Script does automatic conversions as needed, explicit conversions are hardly ever needed 13
Variables n n n Every variable is a property of an object When Java. Script starts, it creates a global object In client-side Java. Script, the window is the global object n n n There can be more than one “global” object n n It can be referred to as window or as this The “built-in” variables and methods are defined here For example, one frame can refer to another frame with code such as parent. frames[1] Local variables in a function are properties of a special call object 14
HTML names in Java. Script n In HTML the window is the global object n n n It is assumed that all variables are properties of this object, or of some object descended from this object The most important window property is document HTML form elements can be referred to by document. forms[form. Number]. elements[element. Number] n Every HTML form element has a name attribute n n The name can be used in place of the array reference Hence, if n n n <form name="my. Form"> <input type="button" name="my. Button". . . > Then instead of document. forms[0]. elements[0] you can say document. my. Form. my. Button 15
More about with n n n with (object) statement ; uses the object as the default prefix for variables in the statement As noted in an earlier lecture, one book hints at mysterious problems resulting from the use of with, and recommends against ever using it It turns out that there are two problems: n n with is difficult to optimize, hence may be inefficient More importantly, variable declarations and function definitions have odd and counterintuitive behavior n n The problem appears to be determining if the prefix is used Other types of statements are fine 16
Functions n n n In Java, methods are associated with objects In Java. Script, a function is an object Functions can be recursive: n n function factorial(n) { if (n <= 1) return 1; else return n * factorial(n - 1); } Functions can be nested: n function hypotenuse(a, b) { function square(x) { return x * x; } return Math. sqrt(square(a) + square(b)); } 17
The Function() constructor n Since functions are objects, they have a constructor: n n Notice that the function has no name n n n But you can assign it to a variable and use that name The name can be used to call the function as usual You can construct functions dynamically in Java. Script (they are automatically compiled) n n Function(arg 1, arg 2, . . . , arg. N, body) All the arguments to the constructor are strings Example: var f = new Function("x", "y", "return x * y; "); However, compilation is computationally expensive Functions defined in this way are always global 18
Function literals n As we just saw, a function can be defined by means of a constructor: n n A function can be written literally, as in the following example: n n n var f = new Function("x", "y", "return x * y; "); var f = function(x, y) { return x * y; } This function is not necessarily global To write a recursive literal function, give it a name: n n var f = function fact(n) { if (n <= 1) return n; else return n * fact(n - 1) ; }; The name does not persist after the function is created 19
Function names n The “name” of a function is just the variable that holds the function n n n var var var square = function(x) { return x * x; }; a = square(4); // a now holds 16 b = square; // b now holds square c = b(5); // c now holds 25 d = [ b ]; // d is an array e = d[0](6); // e now holds 36 20
The call object n When a function is called, a new call object is created n The properties of the call object include: n n n The function parameters Local variables declared with the var statement The arguments object 21
arguments n The arguments object is like an array n n arguments[n] is a synonym for the nth arguments. length is the number of arguments that the function was called with n n n function. length is the number of arguments it was defined with arguments. length, unlike function. length, is available only within the function arguments. callee is the function itself 22
Example uses of arguments n n function max() { var m = Number. NEGATIVE_INFINITY; for (var i = 0; i < arguments. length; i++) { if (arguments[i] > m) m = arguments[i]; } return m; } function(n) { if (n <= 1) return 1; return n * arguments. callee(n - 1); } 23
Properties of functions I n Functions are objects, and have properties n n length – the number of formal parameters arguments – the Arguments object, which is “like” an array of actual parameters n n n Note: length is not necessarily equal to arguments. length caller – the function that invoked this one, or null if the function was invoked from the top level prototype (for constructor functions) – an object that defines properties and methods of functions created with this constructor 24
Properties of functions II n Since a function is an object, you can add properties to it n n n Function properties are often a good alternative to global variables Example: unique. Integer. counter = 0; function unique. Integer() { return unique. Integer. counter++; } Function properties are a bit like static variables in Java 25
Global and local variables n A variable is local to a function if n n It is a formal parameter of the function It is declared with var inside the function (e. g. var x = 5) Otherwise, variables are global Specifically, a variable is global if n n It is declared outside any function (with or without var) It is declared by assignment inside a function (e. g. x = 5) 26
Functions and methods n When a function is a property of an object, we call it a “method” n n A method can be invoked by either of call(object, arg 1, . . . , arg. N) or apply(object, [arg 1, . . . , arg. N]) call and apply are defined for all functions n n call takes any number of arguments apply takes an array of arguments Both allow you to invoke a function as if it were a method of some other object, object Inside the function, the keyword this refers to the object 27
Methods I n First we construct an object: n n function Point(xcoord, ycoord) { this. x = xcoord; // keyword "this" is mandatory this. y = ycoord; } my. Point = new Point(3, 5); A method is a function that is associated with, and invoked through, an object (hence can use this) Here is a “function” that makes no sense by itself: n function distance(x 2, y 2) { function sqr(x) { return x * x; } return Math. sqrt(sqr(this. x – x 2) + sqr(this. y – y 2)); } 28
Methods II n We can turn this function into a method, like so: n n Now this inside the function refers to my. Point, and we can say: n n document. write("The distance is " + distance. call(my. Point, 6, 9)); Or: n n document. write("The distance is " + my. Point. dist(6, 9)); If we don’t want to permanently associate the function with my. Point, but just use it briefly, we can say: n n my. Point. dist = distance; document. write("The distance is " + distance. apply(my. Point, [6, 9])); The difference between these two Function methods is: n n call takes an object and an arbitrary number of actual parameters apply takes an object and an array of actual parameters 29
Methods III n n The previous slide showed how to attach a method to a single object To attach a method to all objects created by a given constructor, add it to the prototype property of the constructor n n Point. prototype. dist = distance; The to. String method is a particularly useful one to add: n Point. prototype. to. String = function() { return "(" + this. x + ", " + this. y + ")"; }; 30
The End 31
4-advanced-javascript.ppt