JavaScript Programming Chris Seddon seddon-software@keme.co.uk 2000-12 CRS Enterprises Ltd 1
2000-12 CRS Enterprises Ltd 2
JavaScript Resources General: http://www.w3.org http://www.devguru.com/technologies/ecmascript/quickref/javascript_ind ex.html http://www.w3schools.com Videos: http://video.search.yahoo.com/search/video;_ylt=a0og7lohkqzpa3ua8y ZXNyoA?p=douglas+crockford+javascript+the+good+parts&fr=ushvideo&fr2=piv-web Refcardz: http://refcardz.dzone.com/ Copyright 2000-12 CRS Enterprises Ltd 3 2000-12 CRS Enterprises Ltd 3
History 1992 Oak, Gosling at Sun & FirstPerson 1995 HotJava LiveScript, Eich at Netscape 1996 JScript at Microsoft 1998 ECMAScript Copyright 2000-12 CRS Enterprises Ltd 4 2000-12 CRS Enterprises Ltd 4
Events <button onclick="copytext()">copy Text</button> Attach handlers to elements in the DOM onabort onblur onblur onchange onclick onclick ondblclick ondragdrop onerror onfocus onkeydown onkeypress onkeyup onload onload onmousedown onmousemove onmouseout onmouseover onmouseup onmove onreset onresize onselect onsubmit onunload Copyright 2000-12 CRS Enterprises Ltd 5 2000-12 CRS Enterprises Ltd 5
DOM Objects Built in DOM Objects can be used in the browser Anchor Applet Area Array Boolean Button Checkbox Date Document Event FileUpload Form Frame Function Hidden History Image LayerLink Location Math Navigator Number Object Option Password Radio RegExp Reset Screen Select String Submit Text Textarea Window Copyright 2000-12 CRS Enterprises Ltd 6 2000-12 CRS Enterprises Ltd 6
JavaScript Global Functions Several global funtions available: escape eval isfinite isnan number parsefloat parseint String Taint unescape untaint parsefloat('1.45kg'); // // 1.45 1.45 eval("x=10;y=20;document.write(x*y)"); // // 200 200 escape(today? or or tomorrow!"); //Today%3F%20tomorrow%21 Copyright 2000-12 CRS Enterprises Ltd 7 2000-12 CRS Enterprises Ltd 7
Data Types Numbers only floating point Strings Booleans Objects name, value pairs prototype inheritance undefined null Copyright 2000-12 CRS Enterprises Ltd 8 2000-12 CRS Enterprises Ltd 8
Numbers Only one number type no integers 64-bit floating point Not exact: 0.1 + 0.2 = 0.30000000000000004 NaN (Not a Number) result of undefined or erroneous operations any arithmetic operation with NaN as an input will have NaN as a result NaN is not equal to anything, including NaN Copyright 2000-12 CRS Enterprises Ltd 9 2000-12 CRS Enterprises Ltd 9
Strings Sequence of 0 or more 16-bit characters immutable single or double quotes No separate character type characters are represented as strings with a length of 1 String to a number It produces NaN if it has a problem var n = Number("5.76") Number to string It stops at the first non-digit character radix can be specified var s = parseint(5.76) Copyright 2000-12 CRS Enterprises Ltd 10 2000-12 CRS Enterprises Ltd 10
Undefined and Null A lot of confusion especially if you use == undefined a variable that has not been assigned default value var var x; x; null an object with no value '' '' == == '0' '0' // // false false 0 == == '' '' // // true true 0 = '0' '0' // // true true false false == == 'false' // // false false false == == '0' '0' // // true true false false == == undefined // // false false false false == == null null // // false false null null == == undefined // // true true " \t\r\n " == == 0 // // true true var var x = null; null; Always compare with === or!== Copyright 2000-12 CRS Enterprises Ltd 11 2000-12 CRS Enterprises Ltd 11
Statements if switch while do for break continue return try/throw Copyright 2000-12 CRS Enterprises Ltd 12 2000-12 CRS Enterprises Ltd 12
Loops Like Java... for(;;) for in while do while for(i for(i = 0; 0; i i < a.length; i++) i++) {{ if(a[i] === === target) break; document.write("..."); }} deep semantics for for (var (var name name in in object) object) {{ if if (object.hasownproperty(name)) {{ document.write("..."); }} }} Copyright 2000-12 CRS Enterprises Ltd 13 2000-12 CRS Enterprises Ltd 13
Switch statement Multiway branch switch value does not need to a number - can be a string case values can be expressions switch switch (favoritemovie) {{ case case "Titanic": alert("not a bad bad choice!"); break; break; case case "Water "Water World": World": alert("no comment"); break; break; case case "Scream 2": 2": alert("it alert("it has has its its moments"); break; break; default default :: alert("i\'m sure sure it it was was great"); great"); }} Copyright 2000-12 CRS Enterprises Ltd 14 2000-12 CRS Enterprises Ltd 14
Exceptions try - throw - catch as in Java Can have a finally clause var var txt; txt; function message() {{ try try {{ f("welcome guest!"); }} catch (err) (err){{ txt txt = "\n\nthere was was an an error error on on this this page."; alert(err + txt); txt); }} }} Copyright 2000-12 CRS Enterprises Ltd 15 2000-12 CRS Enterprises Ltd 15
Try Statement The JavaScript implementation can produce these exception names: 'Error' 'EvalError' 'RangeError' 'SyntaxError' 'TypeError' 'URIError' Copyright 2000-12 CRS Enterprises Ltd 16 2000-12 CRS Enterprises Ltd 16
With statement Intended as a short-hand ambiguous error-prone aaa.bbb.ccc.x = true; true; aaa.bbb.ccc.y = true; true; with with (ooo.eee.oo.ah_ah.ting.tang.walla.walla) {{ x = true; true; y = true; true; }} does this change x and y or aaa.bbb.ccc.x and aaa.bbb.ccc.y Don't use it! Copyright 2000-12 CRS Enterprises Ltd 17 2000-12 CRS Enterprises Ltd 17
Var statement Defines variables within a function. Types are not specified. Initial values are optional. var varname; var varnrerrors = 0; 0; var vara, a, b, b, c; c; Copyright 2000-12 CRS Enterprises Ltd 18 2000-12 CRS Enterprises Ltd 18
Arrays Array inherits from Object indexes are converted to strings and used as names for retrieving values Very efficient for sparse arrays not very efficient in most other cases no need to provide a length or type when creating an array var var a = new new Array(); a[3] a[3] = 300; 300; a[44] = 4400; a[-20] = 2000; a["abc"] = 66; 66; Array length is meaningless for sparse arrays print("array length = "" + a.length); Array Array length length = 45 45 Copyright 2000-12 CRS Enterprises Ltd 19 2000-12 CRS Enterprises Ltd 19
Array Literals An array literal uses [ ] It can contain any number of expressions, separated by commas mylist = ['oats', 'peas', 'beans']; New items can be appended mylist[mylist.length] = 'barley'; The dot notation should not be used with arrays [ ] is preferred to new Array() Copyright 2000-12 CRS Enterprises Ltd 20 2000-12 CRS Enterprises Ltd 20
Array Methods concat join pop push slice sort splice join two or or more arrays joins the elements of of an an array into a string removes the last element and return it it add new elements to to the end of of an an array returns sub-array sorts elements splice in in new array replacing part of of original Copyright 2000-12 CRS Enterprises Ltd 21 2000-12 CRS Enterprises Ltd 21
Objects No formal definition of a class JavaScript uses objects Objects have properties properties have values properties can be objects with properties no encapsulation (public/private) Prototype Inheritance classical inheritance is not supported Copyright 2000-12 CRS Enterprises Ltd 22 2000-12 CRS Enterprises Ltd 22
Dynamic Objects Unification of Object and hashtable new Object() Hash nature is hidden produces an empty container of name/value pairs members can be accessed with dot notation or subscript notation var var book = new new Object(); book.title = "JavaScript Book"; var var book.chapter1 = new new Object(); book.chapter1.title = "Chapter 1"; 1"; book.chapter1.pages = 23; 23; Copyright 2000-12 CRS Enterprises Ltd 23 2000-12 CRS Enterprises Ltd 23
Creating Objects Make a new empty object {} is the preferred form. var varp1 p1 = new newobject(); var varp2 p2 = {{}; }; Creating populated objects var var p1 p1 = new new Object(); p1.x p1.x = 44; 44; p1.y p1.y = 45; 45; var var p2 p2 = {'x': {'x': 54, 54, 'y': 'y': 55}; 55}; Copyright 2000-12 CRS Enterprises Ltd 24 2000-12 CRS Enterprises Ltd 24
Accessing Objects Create object: var var p1 p1 = {'x': {'x': 44, 44, 'y': 'y': 55}; 55}; Attributes can be accessed using [ ] or dot notation: document.write(p1['x'], p1['y'); document.write(p1.x, p1.y); Members can be removed from an object with the delete operator: delete p1['x'] Copyright 2000-12 CRS Enterprises Ltd 25 2000-12 CRS Enterprises Ltd 25
Object Literals Can be nested... var var myobject = {{ name: name: "Jack "Jack B. B. Nimble", 'goto': 'goto':'jail', 'Jail', grade: grade: 'A', 'A', format: {{ type: type: 'rect', 'rect', width: width: 1920, 1920, height: height: 1080, 1080, interlace: false, false, framerate: 24 24 }} }; }; Copyright 2000-12 CRS Enterprises Ltd 26 2000-12 CRS Enterprises Ltd 26
Prototype Inheritance... JavaScript use prototype inheritance unfamiliar to classical programmers object inheritance, not class inheritance An object can inherit from an older object prototype property defines linkage Copyright 2000-12 CRS Enterprises Ltd 27 2000-12 CRS Enterprises Ltd 27
... Prototype Inheritance function Rectangle(h, w) w) {{ function NamedRectangle(h, w, w, name) name) {{ this.h this.h = h; h; this.prototype = Rectangle; this.w this.w = w; w; this.prototype(h, w); w); this.area = function() {{ this.name = name; name; return return this.h this.h ** this.w; this.w; }} }; }; }} var var p1 p1 = new new Rectangle(7, 8); 8); var var area area = p1.area(); print(area); var var p2 p2 = new new NamedRectangle(3, 6, 6, "small"); area area = p2.area(); print(area); Copyright 2000-12 CRS Enterprises Ltd 28 2000-12 CRS Enterprises Ltd 28
Extension Methods Prototype inheritance allows addition of methods to existing classes String.prototype.sayHello = function() {{ print("hello to to "" + this); }; }; "Chris".sayHello(); Copyright 2000-12 CRS Enterprises Ltd 29 2000-12 CRS Enterprises Ltd 29
Arrays v Objects Arrays are implemented as hash tables not continguous memory Use arrays when the names are sequential integers length property makes sense Use objects when the names are arbitrary strings using arrays in this situation can be confusing Copyright 2000-12 CRS Enterprises Ltd 30 2000-12 CRS Enterprises Ltd 30
Arrays and Inheritance Don t use arrays as prototypes. The object produced this way does not have array nature. It will inherit the array's values and methods, but not its length. You can augment an individual array. Assign a method to it. This works because arrays are objects. You can augment all arrays. Assign methods to Array.prototype Copyright 2000-12 CRS Enterprises Ltd 31 2000-12 CRS Enterprises Ltd 31
Reference Objects can be passed as arguments to functions, and can be returned by functions Objects are passed by reference. Objects are not passed by value. The === operator compares object references, not values true only if both operands are the same object Copyright 2000-12 CRS Enterprises Ltd 32 2000-12 CRS Enterprises Ltd 32
Function Objects... Functions are objects so they can contain name/value pairs can serve the same purpose as static members in other languages no implicit type checking on the arguments If a function is called with too many arguments extra arguments are ignored If a function is called with too few arguments the missing values will be undefined Copyright 2000-12 CRS Enterprises Ltd 33 2000-12 CRS Enterprises Ltd 33
... Defining Function Objects Three different ways to define functions: 1. function sayhello(arg1,arg2) {{ // // function content content goes goes here here }} 2. var var sayhello = function(arg1,arg2) {{ // // function content content goes goes here here }; }; 3. var var sayhello = new new Function("arg1", "arg2", "arg2","print(arg1, arg2"); arg2"); Copyright 2000-12 CRS Enterprises Ltd 34 2000-12 CRS Enterprises Ltd 34
Methods... Since functions are values, functions can be stored in objects a function in an object is called a method. var var myobject = {{ value: value: 0, 0, increment: function (inc) (inc){{ if(typeof inc inc === === 'number') {{ this.value += += inc; inc; }} else else {{ this.value += += 1; 1; }} }} }; }; myobject.increment(2); print(myobject.value); myobject.increment(); print(myobject.value); Copyright 2000-12 CRS Enterprises Ltd 35 2000-12 CRS Enterprises Ltd 35
... Methods Variations on the method pattern: var var myobject = function() {{ return return {{ anonymous object hello hello ::"Hello", "Hello", saygoodbye :: function() {{ print("goodbye"); }} }; }; }(); }();//// execute and and return return immediately print(myobject.hello); myobject.saygoodbye(); Copyright 2000-12 CRS Enterprises Ltd 36 2000-12 CRS Enterprises Ltd 36
Arguments When a function is invoked, in addition to its parameters, it also gets a special parameter called arguments. it contains all of the arguments from the invocation an array-like object function sum() sum() {{ var var total total = 0; 0; for for (var (var i i = 0; 0; i i < arguments.length; i i += += 1) 1) {{ total total += += arguments[i]; }} return return total; total; }} var var result result = sum(6, sum(6, 4, 4, 9, 9, 3, 3, 7, 7, 2); 2); print(result); Copyright 2000-12 CRS Enterprises Ltd 37 2000-12 CRS Enterprises Ltd 37
More on Functions Scope {blocks} do not have scope only functions have scope. vars defined in a function are not visible outside of the function Return statement if there is no expression, then the return value is undefined except for constructors, whose default return value is this Inner functions functions can be nested Copyright 2000-12 CRS Enterprises Ltd 38 2000-12 CRS Enterprises Ltd 38
Closure The scope of an inner function continues even after the parent functions have returned This is called closure var var v = function() {{ var var hello hello = "Hello"; "Hello"; var var saygoodbye = function() {{ print("goodbye"); }; }; var var obj obj = {{ a :: hello, hello, b :: function() {{ print(hello); saygoodbye(); }} }; }; return return obj; obj; }(); }();//// execute and and return return immediately print(v.a); v.b(); v.b(); Copyright 2000-12 CRS Enterprises Ltd 39 2000-12 CRS Enterprises Ltd 39
Comparison == and!== use type coercion with confusing results don't use === and!=== don't use coercion sensible results value = myobject[name] if(value == == null) null) {{ alert(name + '' not not found') }} bad value = myobject[name]; if(value === === undefined) {{ alert(name + '' not not found'); }} good Copyright 2000-12 CRS Enterprises Ltd 40 2000-12 CRS Enterprises Ltd 40
Style Matters Be careful with { } use Java style braces problems with optional semicolons return return {{ ok: ok: false false }; }; return return ;; {{ ok: ok: false false ;; }; }; wrong return return {{ ok: ok: false false ;; }; }; return return {{ ok: ok: false; false; }} correct Always insert semi-colons Copyright 2000-12 CRS Enterprises Ltd 41 2000-12 CRS Enterprises Ltd 41
Crockford's JavaScript Toolkit Look at Douglas Crockford's Remedial JavaScript Contains a small, but useful toolkit of JavaScript functions var var template = '<table '<table border="{border}">' + '<tr><th>last</th><td>{last}</td></tr>' + '<tr><th>first</th><td>{first}</td></tr>' + '</table>'; var var data data = {{ first: first: "Carl", "Carl", last: last: "Hollywood", border: 2 }; }; mydiv.innerhtml = template.supplant(data); http://javascript.crockford.com/remedial.html Copyright 2000-12 CRS Enterprises Ltd 42 2000-12 CRS Enterprises Ltd 42
Global Variables are Dangerous Functions within an application can clobber each other Cooperating applications can clobber each other Use of the global namespace must be minimized Copyright 2000-12 CRS Enterprises Ltd 43 2000-12 CRS Enterprises Ltd 43
Implied Global Any var which is not properly declared is assumed to be global by default This makes it easy for people who do not know or care about encapsulation to be productive but it makes applications less reliable. JSLint is a tool which helps identify implied globals and other weaknesses http://www.jslint.com Copyright 2000-12 CRS Enterprises Ltd 44 2000-12 CRS Enterprises Ltd 44
Namespace Every object is a separate namespace use an object to organize your variables and functions var var AMADEUS = {}; {}; display display = function(o) function(o) {{ for(key for(key in in o) o) {{ document.write(key, ":", ":", o[key]); o[key]); }} }; }; AMADEUS.myObject = {{ x:200, y:500 }; }; display(amadeus.myobject); Copyright 2000-12 CRS Enterprises Ltd 45 2000-12 CRS Enterprises Ltd 45
Encapsulate Function scope can create an encapsulation must use an anonymous function to wrap your application This works identifier optional (function(){ alert(2 alert(2 + 2); 2); })(); })(); FunctionExpression :: function Identifieropt (FormalParameterListopt) {FunctionBody} This fails to compile identifier mandatory function(){ alert(2 alert(2 + 2); 2); }(); }(); FunctionDeclaration :: function Identifier (( FormalParameterListopt )){FunctionBody} Copyright 2000-12 CRS Enterprises Ltd 46 2000-12 CRS Enterprises Ltd 46
RegExp Regular expression pattern matcher var var parse_number = RegExp( "^" "^" + // // start start of of line line "-?" "-?" + // // optional -- "\\d+" "\\d+" + // // digits digits "(?:\\.\\d*)?" + // //.. digits digits "(?:e[+\\-]?\\d+)?" + // // optional exponent "$","i"); "$","i"); // // end end of of line line "$", "$", // // end end of of line line "i"); "i"); // // ignore ignore case case var var test test = function (n) (n){{ print(parse_number.test(n)); }; }; Copyright 2000-12 CRS Enterprises Ltd 47 2000-12 CRS Enterprises Ltd 47
Threads The language definition is neutral on threads Some language processors e.g. SpiderMonkey provide thread support Most application environments e.g. browsers do not provide thread support Server side engines support threading e.g Java Virtual Machine Copyright 2000-12 CRS Enterprises Ltd 48 2000-12 CRS Enterprises Ltd 48