Documente Academic
Documente Profesional
Documente Cultură
Lecture #
CSE 130
Lecture #
Function Basics
Functions are used to create code fragments that can be used over and over again. Hopefully, these are abstract reusable components, but this is up to the programmer.
function functionname(parameterlist) { statement(s) } where
Functioname must be well-formed JavaScript identifier Parameterlist is a list of JavaScript identifiers separated by commas. The list may also be empty
CSE 130
Lecture #
Function Example 1
Simple function with no parameters
function sayHello() { alert("Hello there"); } sayHello(); // invoke the function
Note: You generally will be unable to call a function before it is defined. This suggests that you should define your functions in the <head> of your (X)HTML document. However, in some JavaScript implementations you can forward reference with the same <script> block.
CSE 130
Lecture #
CSE 130
Lecture #
Example 3: Multiple Parameters & Return function addThree(arg1, arg2, arg3) { return (arg1 + arg2 + arg3); }
CSE 130
Lecture #
Example 4: Multiple Returns function myMax(arg1, arg2) { if (arg1 >= arg2) return arg1 else return arg2; } Note: Functions always return some value whether or not a return is explicitly provided. Usually it is a value of undefined.
CSE 130
Lecture #
Parameter Passing
Primitive Data types are passed by value, in other words a copy of the data is made and given to the function
function fiddle(arg1) { arg1 = 10; document.write("In fiddle arg1 = "+arg1+"<br />"); } var x = 5; document.write("Before function call x = "+x+"<br />"); fiddle(x); document.write("After function call x = "+x+"<br />");
CSE 130
Lecture #
Parameter Passing 2
Composite types are passed by reference in JS
function fiddle(arg1) { arg1[0] = "changed"; document.write("In fiddle arg1 = "+arg1+"<br />"); } var x = ["first", "second", "third"]; document.write("Before function call x = "+x+"<br />"); fiddle(x); document.write("After function call x = "+x+"<br />");
CSE 130
Lecture #
CSE 130
Lecture #
CSE 130
Lecture #
CSE 130
Lecture #
Mask Out
Be careful when you have local and global variables of the same name, you may get an undesirable effect called mask out.
var x = "As a global I am a string"; function maskDemo() { var x = 5; document.write("In function maskDemo x="+x+"<br />"); } document.write("Before function call x="+x+"<br />"); maskDemo(); document.write("After function call x="+x+"<br />");
CSE 130
Lecture #
Local Functions
function testFunction() { function inner1() { document.write("testFunction-inner1<br />"); } function inner2() { document.write("testFunction-inner2<br />"); } document.write("Entering testFunction<br />"); inner1(); inner2(); document.write("Leaving testFunction<br />"); } document.write("About to call testFunction<br />"); testFunction(); document.write("Returned from testFunction<br />"); /* Call inner 1 or inner2 here and error */ inner1();
CSE 130
Lecture #
Functions as Objects
Like nearly everything in JS, functions are objects and can be created and accessed as such
var sayHello = new Function("alert('Hello there');"); sayHello();
CSE 130
Lecture #
Functions as Objects
You can also define functions with parameters in this fashion.
var sayHello2 = new Function("msg","alert('Hello there '+msg);"); sayHello2('Thomas');
CSE 130
Lecture #
CSE 130
Lecture #
CSE 130
Lecture #
Variable Arguments
Given arguments and length you can write more adaptive functions that take variable arguments
function sumAll() { var total=0; for (var i=0; i< sumAll.arguments.length; i++) total+=sumAll.arguments[i]; return(total); } alert(sumAll(3,5,3,5,3,2,6));
CSE 130
Lecture #
CSE 130
Lecture #
Recursive Functions
JS supports recursive functions that call themselves Factorial n! = n*(n-1)*(n-2) * 1
function factorial(n) { if (n == 0) return 1; else return n* factorial(n 1); } alert(factorial(5)); Demo this with negative value in Internet Explorer
CSE 130
Lecture #
Objects in JavaScript
Objects in JavaScript fall into four groups:
Built-in objects (ex. String, Date, Array, etc.) Browser objects (ex. Window, Navigator) Document objects (ex. Document, document.forms[], etc.) User-defined objects
User defined objects are often not used by novice JavaScript programmers but become quite important as you build larger and larger Web applications
CSE 130
Lecture #
Object Creation
Use the new( ) operator along with the appropriate constrictor function
var city = new String(); var city = new String(San Diego); var city2 = San Diego; alert(typeof city); alert(typeof city2);
CSE 130
Lecture #
Object Destruction
We dont have to do much as within browser implementation of JavaScript garbage collection cleans up unused object references we may have
var myString = new String(Larry Fine); myString = new String(Moe Howard); // Larry Fine string eventually garbage collected
Better to hint to the browser you are done with memory though.
var city = new Object(); city = null; // hint to garbage collector
CSE 130
Lecture #
Properties
A property is named data contained in an object
var myString = new String('hello there'); alert(myString.length);
Properties that are not set return undefined Instance properties can be added to a particular object and deleted as well
var myString = new String('hi'); myString.simpleExample = true; alert(myString.simpleExample); delete myString.simpleExample; alert(myString.simpleExample); // undefined
CSE 130
Lecture #
The main uses of this style of syntax is when the property name is a variable or if the property name contains spaces.
CSE 130
Lecture #
Methods
Object properties that are functions are called methods You can use the standard . operator as well as the array syntax to access a method but add the ( ) to invoke the method
var myString = new String("Hi there"); alert(myString.toUpperCase()); alert(myString['toLowerCase']());
Like properties you can set instance methods for a particular objects
myString.sayWhat = function() {alert('What?')}; myString.sayWhat();
CSE 130
Lecture #
Enumerating Objects
The for-in loop can be used to enumerate object properties (and sometimes methods)
for (prop in window.navigator) document.write('window.navigator["' + prop + '"] = ' + window.navigator[prop] + '<br />');
Some browsers may not enumerate methods and some objects particularly built-ins are not enumeratable just instances are
var myString = new String('hi'); myString.foo = true; for (prop in myString) document.write('myString["' + prop + '"] = ' + myString[prop] + '<br />'); for (prop in String) document.write('String["' + prop + '"] = ' + myString[prop] + '<br />'); // nothing
CSE 130
Lecture #
The with statement adds the object to the front of the scope chain during the block of execution trying the used values/methods there first Note the with statement may reduce/increase performance due to less/extra scope resolution
CSE 130
Lecture #
CSE 130
Lecture #
10
CSE 130
Lecture #
Comparing Objects
When comparing primitive types things work as expected, but with objects which are reference types you are comparing a reference to data not the data itself so the comparison may fail
var str1 = "abc"; var str2 = "abc"; alert(str1 == str2); // true str1 = new String("abc"); str2 = new String("abc"); alert(str1 == str2); // false alert(str1.valueOf() == str2.valueOf() ); // true
CSE 130
Lecture #
CSE 130
Lecture #
Object Literals
Object literals have been supported since JS 1.2 and are defined as { name1 : value1, name-n: value-n;}
var robot2 = { name: "Arnold", model: "Terminator", hasJetPack: false, attack: function() {alert('Hasta la vista!');} }; alert(robot2.name + " " + robot2.model); robot2.attack();
11
CSE 130
Lecture #
CSE 130
Lecture #
The advantage here is that you can use property names not known until run time
customerName = prompt("Enter name", ""); customerAddress = prompt("Enter address", ""); customers[customerName] = customerAddress; alert(customerName); alert(customers[customerName]);
CSE 130
Lecture #
Constructors
Constructors are special functions that prepare new instances of an object for use
A constructor contains an object prototype that defines the code and data that each object instance has by default
function Robot() { } // caps just convention var guard = new Robot(); function Robot(needsToFly) { if (needsToFly == true) this.hasJetpack = true; else this.hasJetpack = false; } // create a Robot with hasJetpack == true var guard = new Robot(true); // create a Robot with hasJetpack == false var sidekick = new Robot();
12
CSE 130
Lecture #
Prototypes
Every object has a prototype property that gives it its structure. The prototype is a reference to an Object describing the code and data that all objects of that type have in common
Robot.prototype.hasJetpack = false; Robot.prototype.doAction = function() { function Robot(flying) { if (flying == true) this.hasJetpack = true; } var guard = new Robot(true); var canFly = guard.hasJetpack; guard.doAction(); alert(Watch it!"); };
CSE 130
Lecture #
Using Prototypes
Prototypes are of course shared so you can do some interesting things
String.prototype.getThirdChar = function() { return this.charAt(2); } Now you can invoke this method as you would any other built-in String method: var c = "Example".getThirdChar(); // c set to 'a'
Sometimes you dont even need to do prototypes though esp. if you just want to improve some built-in object instances
document.writeln = function(s) { document.write(s + "<br />\n") }; document.writeln('he there'); document.writeln('thomas powell');
CSE 130
Lecture #
13
CSE 130
Lecture #
constructor
toString()
toLocaleString()
valueOf()
hasOwnProperty(prop)
Returns true if the object has an instance property named prop, false otherwise
isPrototypeOf(obj)
Returns true if the object serves as the prototype of the object obj
propertyIsEnumerable(prop)
Returns true if the property give in the string prop will be enumerated in a for/in loop
CSE 130
Lecture #
CSE 130
Lecture #
14
CSE 130
Lecture #
CSE 130
Lecture #
CSE 130
Lecture #
15
CSE 130
Lecture #
Four Models
By studying the history of JavaScript we can bring some order to the chaos of competing object models. There have been four distinct object models used in JavaScript including:
1. 2. 3. Traditional JavaScript Object Model (NS 2 & IE 3) Extended Traditional JavaScript Object Model (NS 3) Dynamic HTML Flavored Object Models 1. a. IE 4 2. b. NS 4 Traditional Browser Object Model + Standard DOM (NS6 & Explorer 5)
4.
CSE 130
Lecture #
CSE 130
Lecture #
Frames[ ]
16
CSE 130
Lecture #
Document Object
The Document object provides access to page elements such as anchors, form fields, and links as well as page properties such as background and text color. Consider
document.alinkColor, document.bgColor, document.fgColor, document.URL document.forms[ ], document.links[ ], document.anchors[ ]
We have also used the methods of the Document object quite a bit
document.write( ) , document.writeln( ), document.open( ), document.close( )
CSE 130
Lecture #
CSE 130
Lecture #
17
CSE 130
Lecture #
Object Access by Associative Array The collection of HTML objects are stored associatively in the arrays. Given the form named myform we might access it using
window.document.forms[myform]
CSE 130
Lecture #
Event Models
JavaScript reacts to user actions through event handlers (code associated with a particular event or object and event in the page) Common events include Click, MouseOver, MouseOut, etc. Events can be registered through HTML event handlers like onclick or via JavaScript directly
<input type=button value=press onclick=alert(hi)> document.onload = new Function(alert(hi));
Well see events primarily with links, form items and mouse movement
CSE 130
Lecture #
All Together
Once document objects are accessed either by user event or script event we can then modify the various properties of the elements. The following examples on the next slides show reading and writing of form fields as a demonstration of this.
18
CSE 130
Lecture #
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Meet and Greet</title> <script language="JavaScript" type="text/javascript"> <!-function sayHello() { var theirname=document.myform.username.value; if (theirname !="") alert("Hello "+theirname+"!"); else alert("Don't be shy."); } // --> </script></head><body> <form name="myform" id="myform"> <b>What's your name?</b> <input type="text" name="username" id="username" size="20"><br><br> <input type="button" value="Greet" onclick="sayHello()"> </form> </body> </html>
CSE 130
Lecture #
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html><head><title>Meet and Greet 2</title> <script language="JavaScript" type="text/javascript"> <!-function sayHello() { var theirname = document.myform.username.value; if (theirname != "") document.myform.response.value="Hello "+theirname+"!"; else document.myform.response.value="Don't be shy."; } // --> </script></head><body> <form name="myform" id="myform"> <b>What's your name?</b> <input type="text" name="username" id="username" size="20"> <br><br> <b>Greeting:</b> <input type="text" name="response" id="response" size="40"> <br><br> <input type="button" value="Greet" onclick="sayHello()"> </form></body></html>
CSE 130
Lecture #
19
CSE 130
Lecture #
CSE 130
Lecture #
CSE 130
Lecture #
20
CSE 130
Lecture #
CSE 130
Lecture #
CSE 130
Lecture #
Summary
This chapter introduces how to access browser and document objects in the traditional manner
By name and by document location
All the various object models were presented from NS 2 to modern day browsers The problem of cross browser compatibility starts to become apparent when you compare the models
21
CSE 130
Lecture #
CSE 130
Lecture #
DOM Flavors
The Document Object Model or DOM is a standard that maps HTML and XML documents into objects for manipulation by scripting languages such as JavaScript The DOM comes in the following flavors:
DOM Level 0 roughly equivalent to NS3s object model. Often called traditional or classic object model DOM Level 1 Maps all the HTML elements and provides generic node manipulation features via the document object. DOM Level 2 Maps all CSS properties Note: The later DOM levels also support the earlier objects so classic scripts should work under DOM
CSE 130
Lecture #
Todays modern browsers like IE 5+ and NS 6+ support DOM Core, DOM HTML, and a good portion of DOM CSS. However, DOM events and DOM XML are not consistently supported
22
CSE 130
Lecture #
Document Trees
The key to understanding the DOM is how an HTML document is modeled as a tree (Didnt we just talk about parse trees!). Consider
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><title>DOM Test</title></head> <body> <h1>DOM Test Heading</h1> <hr> <!-- Just a comment --> <p>A paragraph of <em>text</em> is just an example</p> <ul> <li><a href="http://www.yahoo.com">Yahoo!</a></li> </ul> </body> </html>
CSE 130
Lecture #
CSE 130
Lecture #
23
CSE 130
Lecture #
Node Types
N ode T ype N um b er 1 2 E le m e n t A ttrib u te A n H TM L or X M L e le m e n t. A n a ttr ib u te fo r an H TM L or X M L e le m e n t. A fragm en t o f te x t th a t w o u ld b e e n c lo s e d b y an H TM L or X M L e le m e n t An HTM L com m ent T h e ro o t docum ent o b je c t, n a m e ly th e to p e le m e n t in th e p a r s e tre e A docum ent typ e d e fin itio n < p > < /p > a lig n = c e n te r T ype D e s c r ip tio n E x a m p le
T ext
T h is is a te x t f ra g m e n t!
8 9
10
D o c u m e n tT y p e
< !D O C T Y P E H T M L P U B L IC " //W 3 C //D T D H T M L 4 .0 1 T r a n s itio n a l//E N " " h ttp ://w w w .w 3 .o r g /T R /h tm l4 /lo o s e .d td " >
CSE 130
Lecture #
Node Relationships
Look at the tree for
<p>A paragraph of <em>text</em> is just an example</p>
Notice that the <p> tag has three direct children and one grandchild Also make sure you understand the sibling and parent relationships. The DOM relies on them
CSE 130
Lecture #
24
CSE 130
Lecture #
Accessing Nodes
The easiest way to access nodes in a document tree is via the getElementById( ) method for the Document object. In order to use the method we need to name our tags using the HTML 4 core attribute id like so <p id="p1" align="center">A paragraph of <em>text</em> is just an example</p>
CSE 130
Lecture #
CSE 130
Lecture #
25
CSE 130
Lecture #
n e x tS ib lin g
a ttrib u te s o w n e rD o c u m e n t
CSE 130
Lecture #
Basic Movement
Using the common node properties you should be able to move around a tree that you know the structure of
var currentElement = document.getElementById(p1); currentElement = currentElement.firstChild; currentElement = currentElement.nextSibling; currentElement = currentElement.parentNode;
This simple script would end up right were it started from assuming that the starting node had at least two children.
CSE 130
Lecture #
You should be able to easily write a safe tree traversal system once you know the core properties and how to do if statements
26
CSE 130
Lecture #
getElementsByName
Related to getElementById( ) is the DOM method getElementsByName( ) which deals with HTML elements identifed by the name attribute including: <form>, <input>, <select>, <textarea>, <img>, <a>, <area>, and <frame> Elements using name actually didnt have to have globally unique names thus the DOM method getElementsByName( ) returns a list of nodes with the passed name as shown here looking for something called mytag
tagList = document.getElementsByName('myTag'); for (var i = 0; i < tagList.length; i++) alert(tagList[i].nodeName);
CSE 130
Lecture #
CSE 130
Lecture #
You can use many of these methods on nodes themselves to find the elements within a particular element
allparagraphsinbody = document.body.getElementsByTagName(p); para1=document.getElementById(p1); emElements = para1.getElementsByTagName(em);
27
CSE 130
Lecture #
document.body
<body> tag
document.doctype
should be the <!doctype> statement but may not be and has limited value
CSE 130
Lecture #
Creating Nodes
You can create nodes and then insert them into the document tree
newNode = document.createElement(p);
Of course you may have to then create text nodes to put inside of elements
newText = document.createTextNode(Hello there);
CSE 130
Lecture #
28
CSE 130
Lecture #
CSE 130
Lecture #
Copying Nodes
Use the cloneNode( ) method to make a copy of a particular node. The method take a Boolean argument which indicates if the children of the node should be cloned (a deep clone) or just the node itself var current = document.getElementById(p1); newNode = current.cloneNode(); newSubTree = current.cloneNode(true);
CSE 130
Lecture #
Deleting Nodes
The Node objects removeChild(child) method is useful to delete a node out of the tree. You need to run this node on the parent of the object you are interested in deleting var current = getElementById(p1); currentParent = current.parentNode; currentParent.removeChild(current); Note: The removeChild( ) method does return the node object removed.
29
CSE 130
Lecture #
Replacing Nodes
You can also replace a node using replaceChild(newchild, oldChild) The replaceChildChild( ) method will destroy the contents of the node replace and does not side effect the old value
CSE 130
Lecture #
Modifying Nodes
You cant modify an element directly but you can modify its contents particularly text nodes. Given Use
<p id=p1>This is a test</p> textNode = document.getElementById(p1).firstChild; textNode.data = Ive been changed!;
There are a variety of DOM methods like appendData( ), deleteData( ), insertData( ), replaceData( ), splitText( ), and substringData( ) that can be used, but since the data value is just a string you might want to resort to commonly understood String object methods.
CSE 130
Lecture #
Modifying Attributes
Attributes can be manipulated by DOM methods like getAttribute(name), setAttribute(attributename, attributevalue) and removeAttribute(attributeName) that work off a particular Node object. You can also check for the existence of attributes using the hasAttributes( ) method. Most people do not use these DOM methods but directly modify the attributes of the tag like so <p id=p1 align=left>This is a test</p> You would use current = document.getElementById(p1); current.align = right;
30
CSE 130
Lecture #
CSE 130
Lecture #
CSE 130
Lecture #
then
theElement = document.getElementById(p1); theElement.style.color = green;
What we see is like HTML the various CSS properties map to DOM names directly, so font-size becomes fontSize, background-color becomes backgroundColor, and so on. There are only one or two exceptions to this conversion.
31
CSE 130
Lecture #
CSE 130
Lecture #
DOM Conclusions
The DOM represents the possibility for easier crossbrowser scripting, but it also requires mastery of CSS and HTML to be used properly Some aspects of the BOM are actually easier to use than the DOM
Consider creating nodes or manipulating text contents, some programmers find using properties like innerHTML, innerText, outerText, and outerHTML to be far easier than making nodes one by one
A great deal of legacy code using BOM objects like IEs document.all[ ] style exist and would have to be ported. This will take time!
CSE 130
Lecture #
Summary
JavaScript isnt a toy language
It is very object focused but not in the class manner that is familiar to Java programmers but instead using prototypes The way JS is implemented you dont have to program OOP style if you dont want to Interestingly related as well see even more later to Functional languages like SELF
JS gets nasty when you intersect with the various browser and document object models It is still maturing
http://www.mozilla.org/js/language/ICFP-Keynote.ppt
32