Client-side scripting

JavaScript Elements

• client-side script: code runs in browser a"er page is sent back from server – often this code manipulates the page or responds to user actions

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 2

Why use client-side programming? What is JavaScript?

• PHP already allows us to create dynamic web pages. Why • a lightweight programming language ("scripting language") also use client-side scripting? • • Client-side scripting (JavaScript) benefits: used to make web pages interactive – – usability: can modify a page without having to post back to the server insert dynamic text into HTML (ex: user name) (faster UI) – react to events (ex: page load user click) – efficiency: can make small, quick changes to page without wai?ng for – get information about a user's computer (ex: browser type) server – perform calculations on user's computer (ex: form validation) – event-driven: can respond to user ac?ons like clicks and key presses • a web standard (but not supported identically by all • Server-side programming (PHP) benefits: browsers) – security: has access to server's private data; client can't see source code – compa7bility: not subject to browser compa?bility issues • NOT related to Java other than by name and some syntactic – power: can write files, open connec?ons to servers, connect to databases, ... similarities

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 3 4

Short History of JavaScript JavaScript and JAVA • Originally developed by Netscape, as LiveScript • JavaScript and Java are only related through syntax • Javascript is interpreted • Became a joint venture of Netscape and Sun in • JAVA is strongly typed - types are known at compile time and 1995, renamed JavaScript operand types (τύποι τελεστέων) are checked for • Now standardized by the European Computer compatibility Manufacturers Association as ECMA-262 (also • Variables in JavaScript are dynamically typed ISO 16262) – Compile-time type checking impossible • JavaScript has more relaxed syntax and rules • We’ll call collections of JavaScript code scripts, – fewer and "looser" data types not programs – variables don't need to be declared – errors often silent (few exceptions)

http://www.ecma-international.org/publications/standards/Ecma-262.htm 5 6 JavaScript vs. Java JavaScript vs. PHP

• interpreted, not compiled • similarities: – • more relaxed syntax and rules both are interpreted, not compiled – fewer and "looser" data types + = – both are relaxed about syntax, rules, and types – variables don't need to be declared – both are case-sensitive – errors often silent (few exceptions) – both have built-in regular expressions for powerful text processing • key construct is the function rather than the class • differences: – "first-class" functions are used in many situations – JS is more object-oriented: noun.verb(), less • contained within a web page and integrates with its HTML/ procedural: verb(noun) CSS content – JS focuses on UIs and interacting with a document; PHP on • Objects in: HTML output and files/forms – – JAVA are static: their collection of data members and methods JS code runs on the client's browser; PHP code runs on the web server is fixed at compile time – JavaScript are dynamic: members of an object can change

during execution Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 7 8

Overview of JavaScript Object Orientation and JavaScript

• JavaScript can be used to: • JavaScript is NOT an object-oriented programming – replace some of what is typically done with applets (except language graphics) – Does not support class-based inheritance - cannot support – replace some of what is done with CGI - namely server-side polymorphism programming (but no file operations or networking) – Has prototype-based inheritance, which is much different • User interactions through forms are easy • JavaScript objects are collections of properties, which • The makes it possible to support are like the members of classes in Java and ++ dynamic HTML documents with JavaScript • JavaScript has primitives for simple types – Much of what we will do with JavaScript is event-driven computation

9 10

Linking to a JavaScript file: script

• script tag should be placed in HTML page's head • script code is stored in a separate .js file • JS code can be placed directly in the HTML file's body or head (like CSS) Linking JavaScript to HTML – but this is bad style (should separate content, presentation, and behavior)

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 12 JavaScript in HTML body (example) Browsers and HTML/JavaScript Documents

• What happens when the browser encounters a JavaScript script in a document?

• JS code can be embedded within your HTML • Two approaches for embedding JavaScript in HTML page's head or body documents: – Explicit embedding (ρητή ενσωμάτωση) • runs as the page is loading – mixes HTML content and JS scripts (bad) – Implicit embedding (υπόρρητη ενσωμάτωση) – can cause your page not to validate

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 13 14

Implicit vs Explicit JavaScript JavaScript embedding

• Explicit embedding: • Scripts are usually hidden from browsers that do – Mixes two types of notation inside the same document (bad for readability) not include JavaScript interpreters by putting – Makes maintenance difficult - often different people manage the them in special comments: HTML and the JavaScript – The head of an HTML document - for scripts that produce • This is also required by the HTML validator content only upon request or for those that react to user interactions • Note that the comment closure is in a new line • These scripts contain function definitions and code associated with form and is also a JS comment elements – The body of an HTML document - for scripts that are to be interpreted just once, as they are found

15 16

Event-driven programming

• JS programs have no main; they respond to user actions called events • Event-driven programming: writing programs driven by user events Events in JavaScript • To respond to events, we can write code to respond to various events as the user generates them : event handlers

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 18 Event-driven programming A simple JavaScript Program

• To respond to an event in JavaScript, we follow the following • Problem: create a page with a button that will cause some steps: code to run when it is clicked. – decide which element or control we want to respond to • Step 1: create the HTML Control – write a JavaScript function with the code we want to run (event – button's text appears inside tag; can also contain images handler) – attach that function to the control’s event Javascript example • Event handlers typically cause some sort of change to be

made to the web page:
changing text on the page – dynamically adjusting styles of elements on the page – adding/removing content from the page • Step 2: Write JavaScript Event-Handling Function: – Need to add code to take action when button is clicked – Create a JS file with a function to execute when button is clicked function sayMagicWord() { alert(“PLEASE!”); Event Handler 19 } 20

Pop-up messages in JS A simple JavaScript Program

• JavaScript has three methods for creating dialog boxes: • Step 3: Attach Event Handler to Control – alert, confirm, and prompt – connect JS file to HTML file, using

• type attribute it optional in HTML5; used for backward compatibility • script typically contains no inner content, but not allowed to be a self- closing tag

– attach the sayMagicWord JS function to the click of the button • Every HTML element has special event attributes that represent actions you can perform on it: onclick, onkeydown, onchange, onsubmit • To attach a handler that will “listen” to an event on an element, you set a value for one of the element’s event attributes, which points to the event handler

21 22

Javascript example

– Note: sayMagicWord executes when the user clicks the button, not when the page is loaded

23 24 No Javascript?

Javascript example

Warning: this page requires JavaScript. Please visit this site with a JS-enabled .

JavaScript Syntax

25

8.2 - 8.4: JavaScript Syntax Variables

• 8.1: Key JavaScript Concepts • Names: Variable names begin with a letter or underscore, • 8.2, 8.3, 8.4: JavaScript Syntax followed by any number of letters, underscores, and digits – case sensitive • Object-oriented JavaScript Features • Types: JS determines the type of a variable dynamically, based on the kind of value you assign to it. • Variable declarations: – Explicit: using the keyword var var name = value; – Implicit: it is legal to declare a variable without the var keyword • It is better to avoid this for reasons of programming clarity var name1 = value; name2 = “Marty”;

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst

27 28

Variable scoping Types

of a variable (πεδίο εμβέλειας): the range of statements over • Types are not specified, but JS does have types ("loosely which the variable is visible. typed”) • When JS is embedded in an HTML document, the scope of a variable – Number is the range of lines of the document over which the variable is visible. – Boolean • Implicitly declared variables have global scope, i.e. they are visible in – String the entire HTML document or JS file. – Array – This is true also for implicit variables defined inside a function – Object definition. – Function • Variables explicitly declared inside a function have local scope. – Null – • Global variables: Undefined • explicitly declared variables outside function body • Can find out a variable's type by calling • implicitly declared variables • Local variables: • explicitly declared variables inside a function body

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst

29 30 The typeof function Number type

• given these declarations: • single Number type for and real numbers – function foo() { alert("Hello"); } (no int vs. double) – var a = ["Huey", "Dewey", "Louie"]; • same operators: + - * / % ++ -- = += -= *= /= %= • The following statements are true: • similar precedence to Java – typeof(3.14) === "number" – typeof("hello") === "string" • many operators auto-convert types: – typeof(true) === "boolean" "2" * 3 is 6 – typeof(foo) === "function" – typeof(a) === "object" • NaN (not a number): result of invalid numeric computations, – typeof(null) === "object" such as 1 / “hello” – typeof(undefined) === "undefined" • Constants: Number.MAX_VALUE, Number.MIN_VALUE, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY, Infinity Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 31 32

String type More about String

• Javascript strings represent sequences of characters, and • escape sequences behave as in Java: even individual characters – \' \" \& \n \t \\ • String literals are specified with ‘’ or “ ” • converting between numbers and Strings: • In JS, every value is also an object, containing properties and methods => strings are also objects

• methods: charAt,charCodeAt, fromCharCode, indexOf, • accessing the letters of a String: lastIndexOf, replace, split,substring, toLowerCase, toUpperCase – charAt returns a one-letter String (there is no char type) • length property (not a method as in Java) • concatenation with + : 1 + 1 is 2, but "1" + 1 is "11"

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 33 Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 34

Comments (same as Java)

• identical to Java's comment syntax • recall: 4 comment syntaxes – HTML: DOM and JavaScript – CSS/JS/PHP:/* comment */ – Java/JS/PHP:// comment – PHP:# comment

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 35 Document Object Model (DOM) DOM element objects

• a set of JavaScript objects that represent each element on • every element on the page has a corresponding DOM object the page • access/modify the attributes of the DOM object • most JS code manipulates elements on an HTML page with objectName.attributeName • we can examine elements' state • most DOM object attributes have the same names as the – e.g. see whether a box is checked corresponding HTML attribute • we can change state – img tag's src property – e.g. insert some new text into a div – a tag's href property • we can change styles – e.g. make a paragraph red

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 37 Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 38

Accessing elements through document DOM object properties • The document object represents the entire HTML document • Τhe programmer can use these properties to dynamically and is used to access all of the other DOM objects access and alter page content representing each page element. • document.getElementById returns the DOM object for an element with a given id • Can change the text in most form controls by setting the value property

• The innerHTML property represents the text or HTML content inside an element and can be changed as well. Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 39 Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 40

DOM properties for form controls Modifying text inside an element

• Attributes of HTML elements and their values are also • DOM element objects have the following properties: represented as properties in the element’s DOM object • innerHTML: text and/or HTML tags inside a node • textContent: text (no HTML tags) inside a node – simpler than innerHTML, but not supported in IE6 • value: the value inside a form control

Property Type Description href string Target URL for a link (a) src string Source URL for an image (img) value string Text inside a form control such as an input or text area Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 41 42 Αccessing elements In-class Quiz: Amazing Multiplier

• Write down the code for the following page that computes Javascript example the sum of two numbers:

What do you say?

function sayMagicWord() {

var paragraph = document.getElementById("result"); paragraph.innerHTML = “PLEASE!";

}

43 44

Abuse of innerHTML Μultiplier Example innerHTML can inject arbitrary HTML content into the page • however, this is prone to bugs and errors and is considered

The amazing Multiplier

poor style * • we forbid using innerHTML to inject HTML tags; inject plain = text only
(later, we'll see a better way to inject content with HTML tags
in it)

function compute() {

var input1 = document.getElementById("num1"); var input2 = document.getElementById("num2"); var answer = document.getElementById("answer"); var result = input1.value * input2.value; answer.innerHTML = result; } Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 45 46

Adjusting styles with the DOM Common DOM styling errors objectName.style.propertyName = "value"; JS • many students forget to write .style when setting var clickMe = document.getElementById("clickme"); Don't forget your homework! clickMe.color = "red"; clickMe.style.color = "red"; HTML JS function colorIt() { • var text = document.getElementById("fancytext"); style properties are capitalized likeThis, not like-this text.style.color = "#ff5500"; clickMe.style.font-size = "14pt"; text.style.fontSize = "40pt"; clickMe.style.fontSize = "14pt"; } JS JS • style properties must be set as strings, often with units at the Property Description clickMe.style.widthend = 200; style lets you set any CSS style property for an element clickMe.style.width = "200px"; clickMe.style.padding = "0.5em"; JS • contains same properties as in CSS, but – write exactly the value you would have written in the CSS, but in quotes with camelCasedNames – examples: backgroundColor, borderLeftWidth, fontFamily Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 47 48 In-class Quiz: Amazing Adder Adder Example • Write down the code for the following page that computes the sum of two numbers:

The amazing Adder

+ =

function compute() {

var input1 = document.getElementById("num1"); var input2 = document.getElementById("num2"); var answer = document.getElementById("answer"); var result = input1.value + input2.value; answer.innerHTML = result; }

49 50

What is the result? How to address this?

function compute() {

var input1 = document.getElementById("num1"); var input2 = document.getElementById("num2"); var answer = document.getElementById("answer"); var result = parseInt(input1.value) + parseInt(input2.value); answer.innerHTML = result; }

function compute() { • var input1 = document.getElementById("num1"); parseInt, parseFloat accept a value (typically String) var input2 = document.getElementById("num2"); var answer = document.getElementById("answer"); and translate it into a number or NaN if conversion to number var result = input1.value + input2.value; answer.innerHTML = result; not possible. } • parseInt(“0123”) returns 83. Why? • The value attribute of a DOM tree is represented as a string • + is used for string concatenation 51 52

Convert your name

Name Converter

Type your name ρε: First Last

JavaScript Syntax (ctd’)

function convertName() {

var input = document.getElementById("name"); var name = input.value; var spaceIndex = name.indexOf(" "); var firstName = name.substring(0, spaceIndex); var lastName = name.substring(spaceIndex + 1); lastName = lastName.toUpperCase(); var firstInitial = firstName.charAt(0); input.value = lastName + ", " + firstInitial + "."; }

53 (same as Java) Math object

• methods: abs, ceil, cos, floor, log, max, min, pow, random, round, sin, sqrt, tan • properties: E, PI

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 55 56

Special values: null and undefined Logical operators

• > < >= <= && || ! == != === !== • most logical operators automatically convert types: – 5 < "7" is true – 42 == 42.0 is true • undefined : not a value at all; it represents something that is not specified, declared or defined. – "5.0" == 5 is true – A variable not declared yet, has the value undefined • === and !== are strict equality tests; checks both type and – undefined is what is returned by a function that does not return a value value – "5.0" === 5 is false • null : indicates the lack of a value – e.g. document.getElementById returns null when you pass it an id not found in the page

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 57 58

if/else statement (same as Java) Boolean type

• any value can be used as a Boolean – "falsey" values: 0, 0.0, NaN, "", null, and undefined – "truthy" values: anything else

• identical structure to Java's if/else statement • converting a value into a Boolean explicitly: – var boolValue = Boolean(otherValue); • JavaScript allows almost anything as a condi1on – var boolValue = !!(otherValue);

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 59 60 while loops (same as Java) Common JS Errors

• Fail to link to JavaScript file properly – Fix: place an alert at the top of your .js file as a sanity check, and/or use or Chrome Dev

• and keywords also behave as in Java break continue • Trying to access an undefined object or property – Use Firebug or Chrome Dev to find the line with an error, and double check relevant expressions

• Use JSLint: paste your code on the JSLint syntax verifier • Add “use strict”; at the very top of your JS file

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 61 62

Why use classes and objects? • small programs are easily written without objects • JavaScript treats functions as first-class citizens • larger programs become cluttered with disorganised functions Objects and Arrays in JavaScript • objects group related data and behaviour – helps manage size and complexity, promotes code reuse • You have already used many types of JavaScript objects – Strings, arrays, HTML / XML DOM nodes – Prototype .Request, etc

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst

64

JavaScript objects JavaScript objects

• Objects are dynamic collections of property-value pairs: • An object can represent: – Properties are names – Unordered collection of named values – • Data properties (primitive values and references to Ordered collection of numbered values: array – objects) An entity that has executable code associated with it: function (all functions are objects and are referenced through • Method properties (methods) variables) – Values are data or functions • Because these three kinds of objects behave differently, • Objects are accessed indirectly through variables we treat them as distinct datatypes – The properties of an object are referenced by attaching • There are also specialised objects which represent new the name of a property to the variable that references the classes of objects: Date, RegExp, Error object. E.g. myCar.engine

65 66 Arrays Array methods

• Objects with some special functionality – Array elements can be primitive values or references to other objects Μethod Description – Length is dynamic - the length property stores the length concat(array1,…,arrayN) Join two or more arrays and returns new array indexOf(value) index of first occurrence of value (-1 if not found) • Array objects can be created in two ways, with new, or by assigning an array literal join(), join(separator) Returns string of joined array elements (optional – var myList = new Array(24, "bread", true); separator is comma) – var myList2 = [24, "bread", true]; lastIndexOf(value) Index of last occurrence of value (-1 if not found) – var myList3 = new Array(24); pop() Removes and returns last element of array • The length property of an array is the highest subscript to which an push(value1,..,valueN) Adds one or more elts to end of array element has been assigned, plus 1 reverse() – myList[122] = "bitsy"; // length is 123 shift() Removes and returns the first element of the array • Because the length property is writeable, you can set it to make the unshift(val1,..,valN) Adds one or more elements to the front of an array sort() array any length you like, as in: Sorts elements in place toString() Converts array into a string “1, 2, 3” – myList.length = 150; every, Advanced iteration, functional programming • Assigning a value to an element that does not exist creates that filter,forEachMap,reuce element , some 67 68

Arrays (continued) Array methods

• Array methods: • array serves as many data structures: list, queue, stack, ... – join – converts all elements of an array to strings and concatenates • methods: concat, join, pop, push, reverse, them into a single string e.g. var listStr = list.join(", "); shift, slice, sort, splice, toString, – reverse unshift – sort – e.g., names.sort(); – push and pop add / remove from back • Coerces elements to strings and puts them in alphabetical order – unshift and shift add / remove from front – concat – catenates its actual parameters to the end of the array – object e.g., newList = list.concat(47, 26); shift and pop return the element that is removed – slice - returns the selected elements in an array, as a new array object • listPart = list.slice(2, 5); • listPart2 = list.slice(2); – toString: Coerce elements to strings, if necessary, and catenate them together, separated by commas (exactly like join(", ")) – push, pop, unshift, and shift Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 69 70

Splitting strings: split and join Arrays as maps (associative arrays)

• split breaks apart a string into an array using a delimiter • the indexes of a JS array need not be integers! – can also be used with regular expressions (seen later) • this allows you to store mappings between an index of any • join merges an array into a single string, placing a delimiter between them type ("keys") and value • similar to Java's Map collection or a hash table data structure

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 71 72 Date object

} methods } getDate, getDay, getMonth, getFullYear, getHours, getMinute s, getSeconds, getMilliseconds,getTime, getTimezoneOffset, parse, setDate, setMonth, setFullYear, setHours, setMinutes,s Functions etSeconds, setMilliseconds, setTime, toString } quirks } getYear returns a 2-digit year; use getFullYear instead } getDay returns day of week from 0 (Sun) through 6 (Sat) } getDate returns day of month from 1 to (# of days in month) } Date stores month from 0-11 (not from 1-12)

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 73

Functions Function definitions

function function_name([formal_parameters]) { • JS interpreter has to see a function definition before it sees a -- body – function call. } – Function definitions are placed in the head of an HTML • Return value is the parameter of return document (either implicitly or explicitly) – If there is no return, or if the end of the function is reached, undefined is – Normally (not always) calls to functions appear in the document returned body – If return has no parameter, undefined is returned • Functions are objects, so variables that reference them can be treated as other object references: – can be passed as parameters – be assigned to other variables – be the elements of an array – can be properties to other objects, in which case they act as methods

function fun() { document.write(“Hello world
;} ref_fun = fun; // ref_fun refers to the fun object fun(); // a call to fun ref_fun(); /* Another call to fun */ 75 76

Parameter passing The arguments array

• Parameters are passed by value, like in C, C++ and Java • Every function contains an array named • When a reference variable is passed (pointing to an object), the arguments representing the parameters passed semantics are essentially pass-by-reference (we can change the object’s contents inside the function). • can loop over them, print/alert them, etc. • There is no type checking of parameters, nor is the number of parameters • allows you to write functions that accept varying numbers of checked (excess actual parameters are ignored, excess formal parameters parameters are set to undefined) • There is no clean way to send a primitive by reference – One dirty way is to put the value in an array and send the array’s name function by10(a) { a[0] *= 10; } ... var listx = new Array(1); ... listx[0] = x; by10(listx); x = listx[0]; Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 77 78 function params(a, b) { document.write("Function params was passed ", arguments.length, " parameter(s)
"); document.write("Parameter values are:
");

for (var arg = 0; arg < arguments.length; arg++) document.write(arguments[arg], "
");

document.write("
"); }

// A test driver for function params

params("Mozart"); params("Mozart", "Beethoven"); params("Mozart", "Beethoven", "Tchaikowsky");

79 80

function median(list) { Functions as parameters list.sort(function (a, b) {return a - b;}); var list_len = list.length; • To sort something other than strings into alphabetical order, // Use the modulus operator to determine whether write a function that performs the comparison and send it to // the array's length is odd or even the sort method // Use Math.floor to truncate numbers // Use Math.round to round numbers • The comparison function must return a negative number, if ((list_len % 2) == 1) zero, or a positive number to indicate whether the order is return list[Math.floor(list_len / 2)]; ok, equal, or not else return Math.round((list[list_len / 2 - 1] + list[list_len/2])/2); function num_order(a, b) {return a - b;} } // end of function median • Now, we can sort an array named num_list with: // Test driver var my_list_1 = [8, 3, 9, 1, 4, 7]; num_list.sort(num_order); var my_list_2 = [10, -2, 0, 5, 3, 1, 7]; var med = median(my_list_1); document.write("Median of [", my_list_1, "] is: ", med, "
"); med = median(my_list_2); document.write("Median of [", my_list_2, "] is: ", med, "
");

81 82

Object creation

• There are different ways to create new objects: – Define and create a single, anonymous object, using an object literal (κυριόλεκτο). – Define and create a single Object, with the keyword new. – Define an object constructor, and then create objects of the Creating JS Objects constructed type, with the keyword new. var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

person = new Object(); person.firstName = “John"; person.lastName = “Doe"; person.age = 50; person.eyeColor = "blue";

function person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; } var myFather = new person("John", "Doe", 50, "blue"); var myMother = new person("Sally", "Rally", 48, "green"); 84 The use of this Object properties

• In JavaScript, this points to the object that "owns" the • Created by assigning a value to a property’s name JavaScript code where this appears. my_car.make = “Ford”; my_car.model = “Contour”; • When used in a function, this is the object that "owns" the my_car.engine = new Object(); -- Object nesting function. my_car.engine.config = “V6”; • When used in an object, this is the object itself. my_car.engine.hp = 200; • Object properties are not variables - they are just • When used in an object constructor, this does not have a names of values, used with object variables to access value. It is only a substitute for the new object. – The value of this will become the new object when the property values. E.g.: constructor is used to create an object. document.write(my_car.engine); • The number of properties in a JavaScript object is dynamic - at any time during interpretation, properties can be added to or deleted from an object. delete(my_car.model);

85 86

Accessing object properties Creating anonymous objects • A property can be accessed the same way it is assigned a value, namely with the object-dot-property notation • Property names can be accessed also as if they were elements of an array: for (identifier in object) • in JavaScript, you can create a new object without creating a statement or compound class for (var prop in my_car) • the above is like a Point object; it has fields named x and y document.write(“Name: ”, prop, “; Value:”, my_car[prop] + "
"); • the object does not belong to any class; it is the only one of its kind – typeof(pt) === "object"

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 87 88

Objects that have behaviour (functions/methods) A poor attempt at a "constructor"

} What if we want to create an en1re new class, not just one object? } JavaScript, unlike Java, does NOT have classes • like in Java, objects' methods run "inside" that object } we could emulate the functionality of a constructor with a – inside an object's method, the object refers to itself as this function: } the above code is ugly and doesn't match the new syntax we're – unlike in Java, the this keyword is mandatory in JS used to

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 89 90 Constructors explained Problems with our constructor

• a constructor is just a normal function • when any function is called with new, JavaScript does the following: • creates a new empty anonymous object and uses it } ugly syntax; every method must be declared inside the as this within the function constructor • implicitly returns the new object at the end of the function } (subtle) replicates the methods in every object (wasteful) • what happens if our "constructor" is called as a normal } every Point object has its own entire copy of function, without new? var p = Point(4, -3); the distanceFromOrigin code

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 91 92

A paradigm shift: prototypes An object's prototype chain

} prototype: an ancestor of a JavaScript object } like a "super-object" instead of a superclass } a parent at the object level rather than at the class level } not to be confused with Prototype framework } every object contains a reference to its prototype } the default is Object.prototype } when you try to look up a property or method in an object, } strings use String.prototype, etc. JavaScript: } a prototype can have a prototype, and so on } Sees if the object itself contains that property/method. } an object "inherits" all methods/data from its prototype(s) } If not, recursively checks the object's prototype to see if it has } it doesn't have to make a copy of them, which saves memory the property/method. } prototypes allow JavaScript to mimic classes and inheritance } Continues up the "prototype chain" until it finds the property/ method or gives up with undefined.

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 93 94

Constructors and prototypes Constructors and prototypes

• When any function called with new, JavaScript does the following: – A new object is created, inheriting from Foo.prototype. – The constructor function Foo is called with the specified • every constructor also has an associated prototype object arguments, and with this bound to the newly created object. – example: when we define our constructor, that creates Point – new Foo is equivalent to new Foo(), i.e. if no argument list is a Point.prototype specified, Foo is called without arguments. – initially this object has nothing in it – The object returned by the constructor function becomes the • every object you construct will use the constructor's result of the whole new expression. prototype object as its prototype • If the constructor function doesn't explicitly return an object, the object – example: every constructed Point object will created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal use Point.prototype object creation process.)

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst

95 96 Modifying a prototype Point prototype methods

} adding a method/field to a prototype will give it to all objects using that prototype } better than manually adding each method to each object (copying the } our Point code could be saved into a file Point.js method N times) } the method works similarly as in Java } we generally put only methods and constant data (not fields!) toString in a prototype object

Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 97 98

Points Example

The amazing Distance

Give Point 1: [ , ]

Give Point 2: [ , ]

The distance is: