Books for College Students. IT 3203 Introduction to Web Development. Creating Objects. Accessing Property Values. What s in an Object?

Size: px
Start display at page:

Download "Books for College Students. IT 3203 Introduction to Web Development. Creating Objects. Accessing Property Values. What s in an Object?"

Transcription

1 Books for College Students IT 3203 Introduction to Web Development JavaScript II Labeling Systems September 24 Notice: This session is being recorded. Copyright 2007 by Bob Brown The Deluxe Transitive Vampire: A Handbook of Grammar for the Innocent, the Eager, and the Doomed Karen Elizabeth Gordon This is one of three books I gave to Megan when she went off to college. The others were The Elements of Style by Strunk and White and How to Solve It by George Polya. Those two should be in the SPSU bookstore. Transitive Vampire is available on Amazon and elsewhere. Creating Objects The new operator creates an object with no properties: var mycar = new Object(); mycar.make = 'Ford'; mycar.model = 'Crown Victoria'; Objects can be nested mycar.engine = new Object; mycar.engine.hp = 200; Accessing Property Values Two equivalent ways: prop1 = mycar.make; prop2 = mycar["make"]; Prefer the first form. Access to properties that don t exist returns an undefined value. Deleting a Property The delete keyword: delete mycar.make; What s in an Object? The for-in operator iterates over the properties of an object: for (var aproperty in mycar){ document.write ("Name: " + aproperty + "; Value: " + mycar[aproperty] + "<br />\n"); 1

2 The Result of for-in Name: make; Value: Ford Name: model; Value: Crown Victoria Name: engine; Value: [object Object] Arrays Arrays are objects with special functionality. Array elements can be: Primitives Objects (including other arrays!) Arrays have dynamic length Creating Arrays There are two ways to create an array With a constructor: var bobsarray = new Array(1, 2, "three"); var billsarray = new Array(100); Implicitly, with an element list var bettysarray = [1, 2, "three"]; Characteristics of Arrays Subscripts start at zero. bobsarray[7] = 132; Arrays have a length property; the length is the highest subscript plus one. The length property is writable! bettysarray.length = 1234; But don t! Only assigned elements occupy space Array Methods tostring: Creates a single string that is the concatenation of all the elements in an array, with comma separators. join: Like tostring, but with a specified separator. reverse: Reverses the order of the elements sort: Sorts the elements alphabetically Concat Concatenates new elements onto an existing array and returns a new array var bobsarray=['1', '2', '3']; bettysarray=['6', '7']; megansarray=bobsarray.concat(bettysarray,'4'); Will be: 1, 2, 3, 6, 7, 4 2

3 Slice Returns a contiguous subset of an array bobsarray = new Array(2,4,6,8,10); billsarray = bobsarray.slice(1,3) Will be: 4,6 A slice two elements long beginning at index 1. From the starting index, up to but not including the ending index. If there s no second parameter, the remainder of the array is copied. Push and Pop Add or remove elements at the end of an array. var reindeer=new Array('Dasher', 'Dancer', 'Donder', 'Blixem'); var lastdeer = reindeer.pop() lastdeer will be Blixem reindeer.push('rudolph'); Now Dasher, Dancer, Donder, Rudolph Donder is Dutch for thunder, so that other reindeer has to be named Blixem and not Blitzen. Shift and Unshift Add or remove elements at the beginning of an array; shift removes ( shifts out ) and unshift inserts. var reindeer=new Array('Dasher', 'Dancer', 'Donder', 'Blixem'); var firstdeer = reindeer.shift(); firstdeer is Dasher reindeer.unshift('rudolph'); Now Rudolph, Dancer, Donder, Blixem Multidimensional Arrays Implement multidimensional arrays as arrays of arrays. var threed = [[2,4,6], [1,3,5], [10,20,30]]; answer = threed[1][2]; answer becomes 5. Associative Arrays JavaScript arrays can use strings as subscripts to form an associative array, also called a hash. var ages = new Array(); ages["megan"] = 23; ages["bob"] = "sixty-harrummmph!" var niece_age = ages["megan"]; // becomes 23 var who = "Megan"; niece_age = ages[who]; // also 23 JavaScript Functions All JavaScript subprograms are functions. Defining a function: function name (params) {// body function myfunc(x) { rvalue = x * x; return rvalue; If no parameters needed, define with empty ( ) 3

4 Functions and Statements If a function returns undefined, it is a stand-alone statement. Otherwise it can participate in expressions, including assignments a = b + myfunc(c); If no parameters are needed, call with empty ( ) Functions Must Be Defined Before Use Function definitions generally go in <head> Define functions before calling them: calls in <body> calls further down in <head> Local Variables var within a function definition creates a local variable. (Implicit definition does not.) Within the function, the local definition takes precedence over globals of the same name. var a=4, b=8; function myfunc() { var a = 0; a is local b = a; b is global Functions and Parameters Formal parameters in the function definition function myfunc(x, y) { x = x*x; return x + y/2; The two a s are not the same! The two b s are the same variable. Parameter Passing Formal parameters in the function definition Actual parameters in the function call function myfunc(x, y) {... z = myfunc(q, r); For primitives, formal parameters receive copies of actual parameters; call by value. For objects, formal parameters receive object references; call by name. Parameters and Side Effects Side effect: A function has a side-effect when it changes some variable outside itself. Generally, this is bad. Return a value instead. Side effects are impossible with primitive parameters, unless you modify a global variable. So, modifying global variables is generally bad. Side effects are possible and even likely when objects are passed as parameters. 4

5 The median Example Median: the middle of a list of elements odd: the value of the middle element even: mean of middle two One approach: use the sort method to sort the array. This has a side effect the array becomes sorted. Bad. Returning from a Function The return statement: returns to the caller passes a value (possibly undefined ) function sq(x) { return x*x; a = sq(2); // a becomes 4 If return is omitted, returns after last executable statement, passes back undefined Number and Type of Parameters JavaScript does no type checking of parameters (use typeof in your functions) JavaScript does not enforce correspondence between the number of formal parameters and the number of actual parameters. Too many actual parameters: excess ignored. Too few: the rest are undefined. The arguments[ ] Array A function s parameters are available in the arguments[ ] array. arguments.length is the number of parameters Can be used to write functions with: a variable number of parameters unnamed parameters Sort Revisited A caller to sort can supply a comparison function that understands the array contents. The function must return: a negative number if items already in order a positive number if a swap is needed zero if items are equal function num_order (a, b) { return a b; numberlist.sort(num_order) ; Reminder: Creating Objects The new operator creates an object with no properties. var mycar = new Object(); mycar.make = "Ford"; Objects can be nested mycar.engine = new Object(); mycar.engine.hp = 200; 5

6 JavaScript Constructors Constructors create and initialize properties of newlycreated objects. Every new expression must include a call to a constructor var mycar = new Object(); The constructor is named the same as the object being created. There are built-in constructors, e.g. Object Writing Constructors A constructor is a function, so you can write your own constructors. Constructor for a Car object: function Car (make, model, year) { this.make = make; this.model = model; this.year = year; this is a reference to the object being created var yourcar = new Car("Ford", "SVT", 2004); var mycar = new Car("Mazda", "RX-7", 1979); Writing Your Own Methods Methods are implemented as functions, so... write a function function display_car () {... then add function to the object in the constructor this.display = display_car; invoke the function through the object mycar.display(); Code for a Method function display_car() { for (var aproperty in this){ // Don't display methods if (typeof(this[aproperty])!= "function") { document.write (aproperty + "=" + this[aproperty] + "<br />\n"); // end of if // end of for // end of function display_car Methods in Constructors New constructor for a Car object: function Car (make, model, year) { this. make = make; this.model = model; this.year = year; this.display = display_car; The right side of the assignment is the name of the function, not a function call! More About Constructors and Objects Objects created by the same constructor have the same set of properties and methods, initially. properties can be added properties can be deleted There is no convenient way to determine whether two objects have the same set of properties or methods. 6

7 Labeling Systems Here is a Web Page Feedback in a conversation is immediate; Feedback when we converse via a Web site is at best delayed. What we call things (labels) are an important part of the conversation. Kinds of Labels Navigation system choices Contextual links Headings Index terms Labels Within Navigation Systems MIND & SPIRIT?!? Labels Within Navigation Systems Labels as Contextual Links 7

8 Labels as Headings Labels as Index Items About Iconic Labels How Jet Blue Fixed It Content Users Context Considerations in Designing Labels General Guidelines Narrow scope Labeling systems, not labels; consider: Style Presentation Syntax Granularity Comprehensiveness Audience 8

9 Sources of Labels Your current site Your competitors Controlled vocabularies, thesauri Search logs Creating Labeling Systems Content analysis Content authors Subject matter experts User advocates Users Usability testing Tuning and Tweaking Review the list Remove duplicates Resolve synonyms Review for consistency Plan ahead Questions 9