• No results found

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

N/A
N/A
Protected

Academic year: 2021

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

Copied!
9
0
0

Loading.... (view fulltext now)

Full text

(1)

IT 3203

Introduction to Web Development

JavaScript II

Labeling Systems

September 24

Copyright © 2007 by Bob Brown

Notice: This session is being recorded.

Books for College Students

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 Styleby Strunk and White and How to Solve Itby George Polya. Those two should be in the SPSU bookstore. Transitive Vampireis available on Amazon and elsewhere.

Creating Objects

The “new” operator creates an object with no properties:

Objects can be nested

myCar.engine = new Object; myCar.engine.hp = 200;

var myCar = new Object(); myCar.make = 'Ford';

myCar.model = 'Crown Victoria';

Two equivalent ways:

Prefer the first form.

Access to properties that don’t exist returns an “undefined” value.

prop1 = myCar.make; prop2 = myCar["make"];

Accessing Property Values

The “delete” keyword: delete myCar.make;

Deleting a Property

The for-inoperator iterates over the properties of an object:

for (var aProperty in myCar){ document.write ("Name: " + aProperty + "; Value: " + myCar[aProperty] + "<br />\n"); }

What’s in an Object?

(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

There are two ways to create an array With a constructor:

Implicitly, with an element list

var bettysArray = [1, 2, "three"]; var bobsArray = new Array(1, 2, "three"); var billsArray = new Array(100);

Creating Arrays

Subscripts start at zero.

Arrays have a length property; the length is the highest subscript plus one.

The length property is writable! Only assigned elements occupy space

bettysArray.length = 1234; bobsArray[7] = 132;

Characteristics of Arrays

But don’t!

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

var bobsArray=['1', '2', '3']; bettysArray=['6', '7'];

megansArray=bobsArray.concat(bettysArray,'4'); Will be: 1, 2, 3, 6, 7, 4

Concat

Concatenates new elements onto an existing array and returns a new array

(3)

bobsArray = new Array(2,4,6,8,10); 0 1 2 3 4 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 includingthe ending index. If there’s no second parameter, the remainder of the array is copied.

Returns a contiguous subset of an array

Slice

Add or remove elements at the end of an array. var reindeer=new Array('Dasher',

'Dancer', 'Donder', 'Blixem');

Push and Pop

lastDeer will be Blixem

Now Dasher, Dancer, Donder, Rudolph var lastDeer = reindeer.pop()

reindeer.push('Rudolph');

“Donder” is Dutch for thunder, so that other reindeer has to be named Blixem and not Blitzen.

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');

Now Rudolph, Dancer, Donder, Blixem

Shift and Unshift

var firstDeer = reindeer.shift();

reindeer.unshift('Rudolph'); firstDeer is Dasher

var threeD = [[2,4,6], [1,3,5], [10,20,30]];

Implement multidimensional arrays as arrays of arrays.

Multidimensional Arrays

answer becomes 5. answer = threeD[1][2];

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:

If no parameters needed, define with empty ( ) function name (params) {// body }

function myfunc(x) { rvalue = x * x; return rvalue; }

(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>

a is local

Local Variables

var a=4, b=8; function myfunc() { var a = 0; b = a; }

“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.

b is global

The two a’s are not the same!

The two b’s are the

same

variable.

Formal parameters in the function definition

function myfunc(x, y) { x = x*x;

return x + y/2; }

Functions and Parameters

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 copiesof actual parameters; call by value.

Parameter Passing

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, unlessyou modify a global variable. • So, modifying global variables is generally bad. • Side effects are possible and even likely when

(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.lengthis 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:

za negative number if items already in order za positive number if a swap is needed zzero 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;

(6)

JavaScript Constructors

Constructors create and initialize properties of newly-created objects.

Every “new” expression must include a call to a constructor

The constructor is named the same as the object being created.

There are “built-in” constructors, e.g. Object var myCar = new 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

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!

Methods in Constructors

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.

(7)

Labeling Systems

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.

Here is a Web Page

Kinds of Labels

• Navigation system choices

• Contextual links

• Headings

• Index terms

Labels Within Navigation Systems

MIND & SPIRIT ?!?

(8)

Labels as Headings

Labels as Index Items

About Iconic Labels

How Jet Blue Fixed It

Considerations in

Designing Labels

• Content

• Users

• Context

General Guidelines

• Narrow scope

• Labeling systems, not labels; consider:

• Style • Presentation • Syntax • Granularity • Comprehensiveness

(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

References

Related documents

• JavaScript has a concept of objects and classes (like in Java) but no built-in concept of inheritance (unlike in Java). &gt; Every JavaScript object is really an instance of

(b) Write a main method that first constructs two Fraction objects representing the fractions 5/7 and 3/8, and then creates two other Fraction objects whose values are the sum

beloved Calamba, Rizal left Manila for Hongkong.” - Jose Rizal, Life, Works and Writings by Gregorio F. Zaide?. • “7

We recorded demographical data, heart rate, mean arterial pressure (MAP), oxygen saturation of hemoglobin (SpO2), RSS value, colonoscopy time, total dose of propofol,

Murach’s JavaScript, C1 © 2009, Mike Murach &amp; Associates, Inc..

Like other European countries, in Spain, a coherent and systematic process en- compassing pre-service education and professional development for VET teachers is still in

With Quickpipe you are going to generate a complete PIPESTRESS input file for a simple piping model in less than 5 minutes, without even knowing anything about

Methods and Constructors (as abstractions for complex user defined operations on objects), methods as mechanisms for side effects; formal arguments and actual arguments in