M150: Data, Computing and Information Unit Nine: Managing complexity through modularity
1- Introduction The unit aims to teach us: The advantages of structuring large complex programs into separate code modules; The benefits of black box programming and the importance of documentation; How to import a function library into a JavaScript program and select and use suitable functions to solve simple programming tasks How to create a fully documented function library; The scoping rules that apply to variables and function names How to use objects in JavaScript; To understand and describe the differences between object types and primitive types; How to create new object types. 2
2- Separate code modules It is easier to understand a complex system if it can be visualized as a system of simple parts which interact within an overall structure Modules and modular programming: is an identifiable piece of program code that implements a particular task. This piece of program code has a name by which it can be identified and so used. A module can be one of a number of identifiable ‘chunks’ within a single file, or it may be a separate file (function and procedure) Most programming languages have mechanisms for constructing a program from a number of separate files rather than writing a single huge program. The programmer writes a main program to solve some problem and ‘imports’ into that program external files of code (modules) that have been written separately (perhaps by other programmers). JavaScript allows you to construct a program from a number of separate files, each containing JavaScript code. A main program file, can indicate that it wants to use JavaScript code from an external file by the simple inclusion of a line of HTML naming that file. 3
2- Separate code modules Types of module that can be implemented in JavaScript (.js files): Function library: is a file containing a collection of related functions (with an extension of .js -short for JavaScript-). Object type: is a file (.js file) holding the code needed to implement new types of objects.( ex. Array and String) Rationale for separate code modules: Real programs can consist of many hundreds of thousands of lines of code Distributing the task of writing the modules (each module is a separate file) among several programmers should shorten the time required to complete a particular programming project. The code modules can be combined later to make up a complete program. 4
2- Separate code modules The Advantages of using modules are: Different aspects of a programming problem may be developed separately. Locating and isolating problems is much easier than would be the case with a monolithic/huge program in a single file (easy to do maintenance). It allows many people to work on the same project, so shortening development time. Modules can be reused and recombined to make up lots of different programs. Modules can be considered as replaceable components which can be easily replaced by improved versions without affecting or making changes to other parts of the program. 5
3- Function libraries Function library: Is an example of module. It is a file that contains functions for future reuse. Function libraries can then be imported into every program in which the functions they contain are needed, avoiding the need to start from scratch each time. ‘Write once, use many times’: save your efforts for use the next time a similar problem is encountered. Copy and paste the required function from the old program into the new one would be both inefficient and error prone. A better solution is to collect reusable functions into files which can then be imported into programs as and when needed. 6
3- Function libraries It isn’t necessary to know or understand the code of these library functions in order to use them (abstraction). To achieve this level of abstraction and make it possible for other programmers to use a function solely/only from its specification, you must document the function precisely. To use function libraries written by other programmers, all that we need to know are (function’s specification): the names of the functions what arguments must be passes to the function and what type of value each must be what the function does results they return (if any, some function just carry out an action) 7
3- Function libraries Black box programming: The use of library functions (or any module) by reference solely to the documentation rather than their implementation. The programmer does not need to know anything about the coding details of a function, which can be hidden from view. All the user need consider is the description of what the black box does, the data that it needs to carry out its task and the result that it returns. You don’t care how the function is implemented. You have been using black boxes (in unit 7 and 8) such as parseFloat() 8
3- Function libraries Importing function libraries in JavaScript To use the functions defined in such a function library, you need to import that library. The effect of importing a function library into a JavaScript program is that the program works as if the contents of the library had been pasted in at the start of the program file. To achieve this you need to add a pair of HTML tags in the HEAD section of the program. This tells the browser where to find the function library. The tags used are a special version of the now familiar SCRIPT tags. They look like plain SCRIPT tags except that they use an attribute called SRC (short for source), to specify where on your computer (or indeed on the internet) the library (the source) can be located 9
3- Function libraries Example1: Example 2: Example 3: Would import all the functions in a function library called myLibrary.js into your program. The library is saved in the same folder as your program Example1: <SCRIPT SRC = myLibrary.js> </SCRIPT> Or <SCRIPT SRC = myLibrary.js> </SCRIPT> Example 2: <SCRIPT SRC = C:\M150\JavaScript\FunctionLibraries\myLibrary.js> Example 3: <SCRIPT SRC=http:/www.somewhere.co.uk/exampleJSCode/myLibrary.js> The function library was in the specified folder A function library at the address given by the URI would be imported into a program 10
3- Function libraries A SCRIPT tag that includes a SRC attribute cannot contain anything else. Your own code must go between a second pair of SCRIPT tags You can access the functions that it contains from within the second pair of SCRIPT tags just as though the functions were actually written within the program 11
3- Function libraries Function library (drawingLibrary.js) is intended to be used as black box. A programmer who writes a function library must be careful to describe the purpose of the file exactly, and the specification of its function. Function specifications for each function in the library are included underneath the function header as comments. It is not necessary and you are not expected to understand the code of the functions in the function library (but you could look at the code) <HTML> <HEAD> <TITLE> An example program that uses drawingLibrary.js </TITLE> <SCRIPT SRC = drawingLibrary.js> </SCRIPT> <SCRIPT> drawSquare('red',5); document.write('<BR>'); drawSquare('blue',5) </SCRIPT > </HEAD> <BODY> </BODY> </HTML> 12
3- Function libraries Example of the documentation for the function library (drawingLibrary.js) /*****************************************************************/ /* Library of simple ascii drawing functions - */ /* Last edit 09/02/04 -RWG */ function drawSquare(colour,indent) /*************************************************************************/ /* Function draws a square, 10 stars wide and 10 stars high. */ /* The function takes two arguments: */ /* colour -a string that specifies the colour of the rectangle. */ /* indent -a whole number which specifies the number of spaces */ /* the rectangle is indented from the left-hand side of the page. */ /* Function returns no value. */ /**************************************************************************/ { …………………} 13
3- Function libraries Example: Write a program that uses functions from drawingLibrary.js to draw a picture Before you start to write this program you will need to read the function specifications for (drawingLibrary.js) and decide which functions to use 14
3- Function libraries Please See the following files: <HTML> <HEAD> <TITLE> Solution_9.3.2 </TITLE> <SCRIPT SRC = "drawingLibrary.js"> </SCRIPT> <SCRIPT> drawRightArrow(30, 'blue', 5); drawRectangle(5, 10, 'red', 5); drawRectangle(5, 10, 'green', 15); drawRectangle(5, 10, 'blue', 25); drawLeftArrow(30, 'red', 5); </SCRIPT> </HEAD> <BODY> </BODY> </HTML> Please See the following files: 1- Solution_9.3.2.html 2- drawingLibrary.js 15
3- Function libraries Example: Write a program that uses functions from drawingLibrary.js to draw a Christmas tree standing in a pot <HTML> <HEAD> <TITLE> Solution_9.3.3</TITLE> <SCRIPT SRC = "drawingLibrary.js"> </SCRIPT> <SCRIPT> drawPyramid(5, 'green', 6); drawPyramid(6, 'green', 5); drawPyramid(7, 'green', 4); drawRectangle(5, 3, 'brown', 9); drawRectangle(7, 7, 'red', 7) </SCRIPT> </HEAD> <BODY> </BODY> </HTML> see Solution_9.3.3 16
4- Programming with function libraries The Date object type We used (in unit 7, 8) a number of JavaScript objects, including the Document and Array object types. We create an object of Array using the reserved word new. Several ways for creating Date object: var today = new Date() new Date() tells JavaScript what kind of object we want. Date() is what is termed a constructor function (a function which is used to initialize a newly-created object into a particular kind of object type – in this case a Date). JavaScript automatically reads your computer’s internal clock setting, and creates a Date object with the date and time at the instant at which the object is created. today object hold the current date and time precisely to the nearest millisecond 17
4- Programming with function libraries You can also create a Date object for a specific date and time (past or future): var myDate = new Date(2004,4,3,12,24,34,15) All arguments except those for the year and month are optional. If they are left out, JavaScript will set them to 00, as follows: var myDate = new Date(2004,4,3,12,24,34) var myDate = new Date(2004,4,3,12,24) var myDate = new Date(2004,4,3,12) var myDate = new Date(2004,4,3) var myDate = new Date(2004,4) year = 2004 month = May day of month=3 hour = 12 minute = 24 second =34 millisecond = 15 4 represents the month The months are ordered from 0 to 11, so May is represented by 4 3 May 2004 at 12.24.00.00 1 May 2004 at 00.00.00.00 18
4- Programming with function libraries To use the 24 hour clock, 3.00pm is represented by the number 15 You can also create dates using a single string argument as follows var myDate=new Date('May 3 2004 11:45:21') var myDate =new Date('May 3 2004 11:45') var myDate = new Date('May 3 2004') There are many methods associated with Date objects, some of them: getFullYear() Returns the year (a four digit number such as 2004) getMonth() Returns the month (a number from 0 to 11) getDate() Returns the day of the month (a number from 1 to 31) getDay() Returns the day of the week (a number from 0 to 6, with 0 representing Sunday, 1 Monday, and so on) getHours() Returns the hour (a number from 0 to 23) getMinutes() Returns the minute (a number from 0 to 59) getSeconds() Returns the second (a number from 0 to 59) Note: if we use a string argument, the full month name must appear in the first, followed by the day of the month, followed by the year and then the time 19
4- Programming with function libraries The following methods can be used to change (or reset) the various elements of a date: setFullYear(year) Sets the year of the Date object (4 digits) setMonth(month) Sets the month in the Date object (0 to 11) setDate(day) Sets the day of the month in the Date object (1 to 31) setHours(hour) Sets the hour in the Date object (0 to 23) setMinutes(minute) Set the minute in the Date object (0 to 59) setSeconds(second) Sets the second in the Date object (0 to 59) Example: To change the year held by myDate to 2005, you write: myDate.setFullYear(2005) To return a four-digit year representing the year in myDate, you write: myDate.getFullYear() 20
4- Programming with function libraries Programming with the dateLibrary.js function library: See Appendix 1 at the end of this unit to read the specification (comments) for all the functions in dateLibrary.js library Some of these functions: isLeapYear() returns Boolean (true) if the date falls in a leap year monthName() returns a string representing the date’s month; noOfDaysInMonth() returns the number of days in the date’s month differenceInDays(dateA, dateB)takes two arguments (both Date objects), returns the difference in days between the two arguments differenceInYears(dateA, dateB) takes two arguments (both Date objects), returns the difference in years between the two arguments displayMonth(theDate) takes one argument( Date object) and displays a calendar for that date's month. 21
4- Programming with function libraries Example1: Write a small program that prints out the day of the week (e.g. Tuesday) on which someone was born <HTML> <HEAD> <TITLE>Solution_9.4.1 </TITLE> <SCRIPT SRC=dateLibrary.js> </SCRIPT> <SCRIPT> var day; var month; var year; var birthDay; year = parseFloat(window.prompt('Enter year as a four-digit number','')); month = parseFloat( window.prompt('Enter month as a number from 1 to 12','')); month = month - 1; day = parseFloat(window.prompt('Enter day as a number from 1 to 31','')); birthDay = new Date(year, month, day); document.write('You were born on a ' + dayName(birthDay)) </SCRIPT> </HEAD> <BODY> </BODY> </HTML> Prompt the user for the year (4-digit) in which they were born and assign it to variable called year.(use parseFloat() to convert String into number) Prompt the user for the month (1 to12) We can’t expect users of the program to know that in JavaScript months are represented by 0 to11!(subtract 1 from the number returned and assign the value to a variable called month Prompt the user for the day of the month (1 to 31) Create a new date object (using the input values year, month and day) Find a function from the dateLibrary that, given a date, returns the day of the week as a result. Finally write out the day of the week year = window.prompt( 'Enter year as a four-digit number',''); year = parseFloat(year); 22
4- Programming with function libraries Example2: Write a program that will tell a user how old they are. The program will write out their age in both years and days. <HTML> <HEAD> <TITLE>Solution_9.4.2 </TITLE> <SCRIPT SRC=dateLibrary.js> </SCRIPT> <SCRIPT> var day, month, year; var birthDay, today; year = parseFloat(window.prompt('Enter year as a four digit number','')); month = parseFloat(window.prompt('Enter month from 1 to 12','')) - 1; day = parseFloat(window.prompt('Enter day as a number from 1 to 31','')); birthDay = new Date(year, month, day); today = new Date(); document.write('You are '+differenceInYears(today,birthDay)+' years old.'); document.write('<BR>'); document.write('Which means that you have been on this Earth for ' + differenceInDays(today, birthDay) + ' days.'); document.write('Have you used your time wisely?') </SCRIPT> </HEAD> <BODY> </BODY> </HTML> First, prompt the user for the year, month and day of their birthday and use those values to create a date. Then you need to create today’s date Next you will need to find two functions in dateLibrary.js, one that takes two dates and returns the difference between them in years and one that takes two dates and returns the difference between them in days. Finally write out the age in both years and days ----------- Output ---------- If you input 2000, 5, 12 You are 8 years old. Which means that you have been on this Earth for 3205 days. Have you used your time wisely? 23
4- Programming with function libraries Example3: Write a program that will display a twelve-month calendar for a particular year <HTML> <HEAD> <TITLE> Solution_9.4.3 </TITLE> <SCRIPT SRC=dateLibrary.js> </SCRIPT> <SCRIPT> var year = parseFloat(window.prompt('Enter year', '')); var date = new Date(year, 0); for (var month = 0; month < 12; month = month + 1) { date.setMonth(month); // update the month displayMonth(date) // display the calendar for that month } </SCRIPT> </HEAD> <BODY> </BODY> </HTML> Prompt the user for their chosen year. Create a date for the January of that year (var date = new Date(year, 0)) Next you will need to write a for loop. The body of the loop will have to execute 12 times, for each value of month from 0 to 11. Each time the loop is executed, the program needs to: - update the Date object so that it represents a different month of the year - then use it as the argument to a function in dateLibrary.js which will print out the month in a calendar format. Output 24
4- Programming with function libraries Notes: In Example1: It is valid in JavaScript to give an expression as the argument to a function (birthDay = new Date(year, month-1, day)). In Example2: we have invoked the methods differenceInYears() and differenceInDays() as part of the arguments to document.write(). We can rewrite document.write('You are '+differenceInYears(today,birthDay)+' years old.') as follows: noOfYears = differenceInYears(today,birthDay); document.write('You are ' + noOfYears + ' years old.'); In Example3: you can rewrite the code using a while loop instead of a for loop as follows: var month = 0; while (month < 12) { date.setMonth(month); displayMonth(date); month = month + 1 } 25
4- Programming with function libraries Extending a function library: You can write function and add it to the date function library. Example: Write a function (and its specification), that prompted the user for year, month and day numbers and returned a Date object as a result. Write the new function in dateLibrary2.js library (use Notepad editor). The function will do the following: Prompt the user for a year (four-digit) between 1900 and 3000 Prompt the user for a month (a number from 1 to 12). Prompt the user for the day of a month (a number from 1 to 31). With the values input, create a Date object and return it from the function If the value returned (for the year, month or day) is not a number in the valid range you will need to repeat the prompt using an appropriate loop. If the value returned is a number the valid range, assign the value to a local variable. 26
4- Programming with function libraries function promptForDate() /*********************************************************************/ /* Function takes no arguments. Prompts user for: */ /* year number from 1900 to 3000 */ /* month number from 1 to 12 */ /* day number from 1 to 31 */ /* Returns a date object. */ { var dayNumber, monthNumber, yearNumber; yearNumber = parseFloat(window.prompt('Enter year number from 1900 to 3000','')); while (yearNumber < 1900 || yearNumber > 3000) yearNumber = parseFloat(window.prompt('Enter year number from 1900 to 3000','')) }; monthNumber = parseFloat(window.prompt('Enter month number from 1 to 12','')); while (monthNumber < 1 || monthNumber > 12) monthNumber = parseFloat(window.prompt('Enter month number from 1 to 12','')) dayNumber = parseFloat(window.prompt('Enter day number from 1 to 31','')); while (dayNumber < 1 || dayNumber > 31) dayNumber = parseFloat(window.prompt('Enter day number from 1 to 31','')) return new Date(yearNumber, monthNumber - 1, dayNumber) } /*************************End of function*****************************/ 27
4- Programming with function libraries The previous example, makes sure that the day of month is from 1 to 31, but some months have only 30 days, and February has 28 or 29 days depending on whether or not the year is a leap year. Modify the function so that invalid day numbers will be rejected. // create a date, given its year and month aDate = new Date(yearNumber, monthNumber -1); // find out the number of days in that month for that year days = noOfDaysInMonth(aDate); dayNumber = parseFloat ( window.prompt('Enter day number from 1 to ' + days,'')); while (dayNumber < 1 || dayNumber > days) { window.prompt('Enter day number from 1 to ' + days,'')) }; 28
4- Programming with function libraries Creating function libraries You can create your own function library from scratch. Function library is simply a text file containing a collection of functions. HTML tags are not allowed or needed, the file contains pure JavaScript. We need to add documentation. A function library that didn’t include the full specifications of all the functions as function comments, would not be very useful at all. You must see (stringLibrary.js) that contains a list of the general purpose String functions that you take them in unit 8. 29
4- Programming with function libraries Scope of variables: Variables can be declared in a number of places in JavaScript programs – at the beginning of a program, within for loop headers, and also within functions. Where a variable is declared in a JavaScript program affects where it can be accessed. Scope of the variable: where in the program it can be referred to by another program statement (the extent of access to a variable) Global variable: which is declared outside any function. It can be accessed from anywhere in the program, including inside the body of any function, whether that function is defined in the program or imported from a function library Local variable: declared within the function, making them inaccessible by name outside the body of the function. It said to be local to that function and are out of scope outside the body of the function. 30
4- Programming with function libraries 31
4- Programming with function libraries function scopeTest() { a = 'cat'; document.write('Inside the function, the value of a is ‘ + a + '<BR>'); }; /* The next line is where a is declared. Since it is declared outside any function, it has global scope.*/ var a a = 'dog'; document.write('Before calling scopeTest(), a is ' scopeTest(); document.write('After calling scopeTest(), a is ' + a + '<BR>') ----------------- The output -------------------- Before calling scopeTest(), a is dog Inside the function, the value of a is cat After calling scopeTest(), a is cat scopeTest() function can access and alter the value of the global variable a that is declared in the main program. Even though the function has finished executing, a retains its value (cat). 32
4- Programming with function libraries If a function does declare a local variable with the same name as a global variable declared in the main program, the variable in the main program becomes inaccessible to that function (the variable in the main program is put into suspended animation). When the function finishes, the global one is released and becomes active again By default variables(v, w, x, y) are available to the function f. But the variable y (that declared in the main program) is unable to permeate through the wall of the function f (it will use the local variable y). This is because the variable y has been declared inside the function f. 33
4- Programming with function libraries function scopeTest2() { var a a = 'cat'; document.write('Inside the function, the value of a is ' + a + '<BR>'); } /* The next line declares a variable with global scope.*/ var a; a = 'dog'; document.write('Before calling scopeTest2(), a is ' scopeTest2(); document.write('After calling scopeTest2(), a is ' ----------------- The output -------------------- Before calling scopeTest2(), a is dog Inside the function, the value of a is cat After calling scopeTest(), a is dog The output differs from that produced in the previous program. This is because the variable a declared in the function scopeTest2() is a different variable, even though it has the same name. This variable is only accessible to code statements within the function. Once the function has finished executing, the JavaScript system will once more understand a as referring to the variable with global scope. 34
4- Programming with function libraries Lifetime of a variable: Global variables exist for as long as the program is running, but local variables are much more temporary and only exist for as long as the function in which they are declared is executing. If the function is called again all its local variables will be recreated (because their previous values will have been lost). function writeOpinions() { var a,b; a = 'I think JavaScript is OK'; b = 'But Smalltalk is better'; document.write(a + '<BR>'); document.write(b + '<BR>') }; var b,c; b = 'There are many programming languages'; c = 'Some are better than others'; document.write(b + '<BR>'); document.write(c + '<BR>'); for (var d=1; d<3; d= d+1) { writeOpinions() } There are many programming languages Some are better than others I think JavaScript is OK But Smalltalk is better 35
4- Programming with function libraries Usually, our declarations have been placed at the start of a program or a function (except of the counter variable for a for loop) It is possible to declare variables elsewhere in the program Usually you declared a variable using the reserved word var. JavaScript also lets you get away with not declaring variables explicitly at all (assign a value to a name without having declared it). In this case the variable would always have global scope, even if you’d first used it in the body of a function. Neglecting to declare your variables is very bad programming practice and can lead to errors that are very difficult to trace A function’s formal argument is a variable that is local to the function. function writeNumber(aNumber) { document.write(aNumber) }; var aNumber, anotherNumber; aNumber = 33; anotherNumber = 45; writeNumber(anotherNumber) 45 36
4- Programming with function libraries Functions, variables and name collisions: Name collisions occur when a global variable has the same name as a function, or another global variable, or when two functions have the same name (which cause a problem- bug in a program) When you import a function library into your program it is as if you had copied and pasted the entire contents of that function library into your program (which may cause collision name). You would need to search for the duplicated variable names and manually renaming variables and functions that have names that have already been used elsewhere. Usually in the function libraries global variables are not declared. The reason was to limit the possibility of name collisions occurring in the programs . To limit the possibilities of name collisions, prefix function and global variable names with the name of the function library, e.g. myLibrary_someVar, instead of simply someVar 37
5- Objects in JavaScript Another modular programming technique – programming with objects. You have already used several JavaScript objects in your programs, for example Date, Array and String objects There is a difference between the object types and data types such as Number and Boolean. Object-oriented programming is one of the most useful ways of constructing modular software. In this approach, a program is structured out of intercommunicating ‘objects’. This idea of viewing software – and, indeed, of designing and writing software – in terms of objects is not a new one, but its value has only really become evident since the late 1980s 38
5- Objects in JavaScript Objects and types: A data type defines a collection of values together with the operations that are allowable on those values. Data type may be: Primitive types (basic types): types that are not defined in terms of other data types . Such as Boolean and number. E.g. 1 and 27 are values belonging to the number data type (27 is a particular instance of the number data type). Examples of allowable operations for number values are +, –, * E.g. true and false are the (only) values belonging to the Boolean data type and examples of allowable operations for such values are >, <, <=, ||, &&. Object types (compound data types): containers that can hold multiple values of different data types (in JavaScript these values are called the object’s properties) together with the code (methods) that operates on those data values (instance). 39
5- Objects in JavaScript E.g. The string 'Good morning!' is example of object belonging to the String object type (String object, or an instance of String object type). String objects have the single property length and examples of allowable operations would be +(concatenation operator) and the method charAt() Object can be named by a single variable even though the object itself may be composed of many data values (of primitive and object type) There are three object categories in JavaScript: Native object types are defined by the JavaScript language. Examples of these are the String, Array, Date, and Math object types. Host object types are supplied to JavaScript by the browser environment (e.g. Internet Explorer or Netscape). Examples of these are Window, Document, and Form object types. Note that the variables window and document (lower-case initial letter), which are particular instances of the Window and Document object types, respectively, are automatically declared for you in any JavaScript program you write. This automatic declaration is not typical of objects (to use a Date object, it must be created with a constructor function and assigned to a variable before it can be used) User-defined object types are defined by you, the programmer. 40
5- Objects in JavaScript Object type defines a collection of properties and methods. Properties are variables: may be either primitive data types or other object types. Because their value may differ from one instance of an object to another, they are often called instance variables. state is the set of values of an object’s instance variables. For example, the state of a particular Date object would consist of the values of its year, month and day properties. Methods are the functions that act on an object’s properties and collectively implement the object’s behaviour. For example a String object has the property length (the length of the string) and methods to perform actions applicable to a string, such as charAt(), fontColor() and italics(). To get an object to execute one of its methods, the method name must be preceded by the object’s variable name and a full stop (.) for example: myString.italics() 41
5- Objects in JavaScript Creation of objects In JavaScript, an object is created by using the object creation operator new, followed by a constructor function that initializes it to be a particular type, i.e. populates the object with properties and methods. For example the code: var today = new Date() will result in the variable today referring to a Date object, in this case a date that represents today’s date. var myArray = new Array(12) the constructor takes one argument and will result in the variable myArray referencing an Array object with 12 elements (all of them undefined). 42
5- Objects in JavaScript Creating new object types: JavaScript enables you to define and create your own object types – user-defined object types. We will create a new object type, Student. Each student object will have the same set of instance variables (properties) – name and courseCode – but the values of the properties will differ from student to student First we need to declare a constructor function: function Student(aName,aCourse) { //object properties this.name = aName; this.courseCode = aCourse } 43
5- Objects in JavaScript Constructor function: Is just a function that has the same name as the type of object we want to create. Unlike ordinary function names, the names of constructor functions start with an upper-case letter. Inside the constructor function we declare appropriate instance variables for the type of object that the constructor function will create, and assign values to them. Inside the constructor function: We don’t need the var reserved word when declaring properties as the “this” reserved word specifies their scope this reserved word is used by JavaScript as a reference to the object that has just been created by the new reserved word. Thus the code in the Student() constructor function assigns the values aName and aCourse to the name and courseCode properties of the newly-created Student object. 44
5- Objects in JavaScript We can create a Student object in the following manner: var studentA = new Student('Joe','M150'); new creates the object but it’s the constructor function that shapes the object into a particular type of object – Student object. What happens when this.name = aName; is executed? First of all, this is a reserved word that JavaScript uses as a reference to the object that has just been created by the reserved word new. Next, the dot notation this.name tells JavaScript to give the object referenced by this a property called name. Finally when the constructor function is called with an actual argument to replace aName ('Joe' in the case), the assignment statement will cause this.name to reference the value of the argument. 45
5- Objects in JavaScript We can access that student’s properties using the dot notation. To assign the value of the name property of studentA to the variable theName (assignment statement). var theName = studentA.name To assign the value of the courseCode property of studentA to the variable theCourse. var theCourse = studentA.courseCode To change the values of an object’s properties: studentA.courseCode = 'M255' studentA.name = 'Jim' Important note: Although the properties of a user-defined object type can always be accessed directly (the object name followed by the property name), this is not always the case for the properties of objects which are instances of JavaScript’s built-in object types. For example, to get and modify the month property of a Date object type, you need to use the methods getMonth() and setMonth(). 46
5- Objects in JavaScript <HTML> <HEAD> <TITLE> Solution_9.5.1 </TITLE> <SCRIPT> function Student(aName, aCourse) { //object properties this.name = aName; this.courseCode = aCourse }; var someStudent; someStudent = new Student('Lindsey', 'M150'); document.write('name is ' + someStudent.name); document.write('<BR>'); document.write('course is ' + someStudent.courseCode); someStudent.name = 'Sarah'; someStudent.courseCode = 'M256'; document.write('name is now ' + someStudent.name); document.write('course is now ' + someStudent.courseCode) </SCRIPT> </HEAD> <BODY> </BODY> </HTML> Example: name is Lindsey course is M150 name is now Sarah course is now M256 47
5- Objects in JavaScript How objects are stored in memory: In primitive data type: Data values such as numbers are stored in the computer’s memory with the variable name acting as a sort of label for the particular memory location in which the value is held. Value semantics ( for the primitive data types): the variable is the address for a block of computer memory. The memory location holds the data value. In Object var studentA = new Student('Joe','M150',34562) Variable studentA refers to (referencing) a Student object. We used the word referencing rather than holding. Reference semantics: the variable holds a reference to the object, rather than the object itself. If you assign an object to a variable, the variable doesn’t hold the value of the object; instead it holds a further memory address which gives the address of the block of memory where the object can actually be found. 48
5- Objects in JavaScript The reason for the difference in storage mechanism stems from the fact that the sizes of objects are not predictable. Each primitive type has a fixed size and, as primitive data types are single data values, it tends to be small. JavaScript allocates an eight-byte block of memory for the storage of any primitive value (although some of this may not be used, depending on the particular type involved). Objects, on the other hand, can be any size, (larger than eight bytes) and so cannot be stored directly in the same way as primitive data types. Instead the memory location ‘labeled’ by a variable will hold: 1- a reference to the first block of memory where the object is stored. 2- the number of blocks of adjacent memory that the object occupies 49
5- Objects in JavaScript The figure below shows how a number and a Student object are stored in memory. The variable aNumber is simply the address in memory of the number that has been assigned to it. aNumber is the address numbered 669 where the number 99 can be directly found. The variable studentA is the address in memory where the address of the object that has been assigned to it can be found. studentA is the address numbered 667 where the address (1500) and size (3 * 8 bytes) of the Student object can be found. 50
5- Objects in JavaScript The different ways in which objects and primitive types are stored in memory is important because it affects the way in which assignment statements work. Consider the following code that demonstrates assignment with the number primitive type. var a = 56; // a now holds the value 56 var b = a; // b now holds the value 56 a = 22 // a now holds the value 22, but b still holds the value 56 Assigning a new value to ‘a’ has not affected the value of ‘b’. Final assignment of primitive data value to variables 51
5- Objects in JavaScript The following code demonstrates assignment with Student objects. var studentA, studentB; studentA = new Student('Meena','M254',76549); The variable studentA holds the address of where to find the newly-created Student object (rather than the object itself). If the following assignment is made: studentB = studentA; studentB will hold a reference to the Student object with the state (property values) 'Meena‘, 'M254', and 76549. The variables studentA and studentB reference the identical Student object. 52
5- Objects in JavaScript If the following expression is executed, studentA.studentID = 27634; JavaScript follows the address held by the variable studentA to find the student object ('Meena', 'M254' 76549). Once the object is found the studentID property is assigned the value 27634. So now the properties of the object referenced by the variable studentA have the values (state) 'Meena', 'M254', 27634. The object referenced by the variable studentB also will be 'Meena', 'M254' and 27634 because the variables studentA and studentB do not hold two different Student objects; they both hold a reference (the address) to the same object (variable studentA and studentB reference the same object) 53
5- Objects in JavaScript If the following expression is executed: var w= 6; var x= 7; var y= ['bill','jane','alice']; var z= [4,5,6]; w = x; z = y; y[1] = 99 The value of w will be 7. The value of x will be 7. The value of y will be a reference to the array ('bill', 99, 'alice'). The value of z will be a reference to the array ('bill', 99, 'alice'). The array with elements 4, 5 and 6 is no longer accessible to the programmer as it is not referenced by any variable. 54
5- Objects in JavaScript Adding behavior – object methods In JavaScript a method is simply a function associated with a given object type, via a statement in its constructor function. The function is defined in the usual way and a statement added to the object constructor to make the function a method for that object type. We can give function the same name as the method. Example: First give the Student object type an additional property, tmaScores, which will be used to reference an array which will hold the scores that a student achieves in each of their TMAs. We need to give the constructor function an extra argument, noOfTmas, which will enable an appropriately sized array to be created by the constructor function. Then, write a method to modify the array referenced by the property tmaScores. 55
5- Objects in JavaScript Two-stage process to add a method updateTmaScores() to the Student object type. First, we will write the function, which we have chosen to call updateTmaResults(). It needs two arguments: the number of the TMA for which a score is to be added or modified (tmaNo), and the score itself (score). Then, associate the updateTmaResults() function with the method name updateTmaScores() for Student objects. We do this by adding another line of code to the Student() constructor function. Note: properties and methods seem similar. They are both variables! Properties hold values such as numbers or references to other objects, while methods are variables that hold references to functions. Indeed in JavaScript functions are actually objects. 56
<HTML> <HEAD> <TITLE>Solution_9.5.4</TITLE> <SCRIPT> function Student(aName, aCourse, idNumber, noOfTmas) { //object properties this.name = aName; this.courseCode = aCourse; this.studentID = idNumber; this.tmaScores = new Array(noOfTmas); //object methods this.updateTmaScores = updateTmaResults }; function updateTmaResults(tmaNo, score) { //arrays in JavaScript are zero based so we deduct 1 from the TMA number this.tmaScores[tmaNo -1] = score /***************************** Main program ****************************/ var student1 = new Student('Sydney', 'M150', 45368, 3); var student2 = new Student('Anaise', 'M150', 54357, 3); student1.updateTmaScores(1, 56); student1.updateTmaScores(2, 67); student1.updateTmaScores(3, 78); student2.updateTmaScores(1, 44); student2.updateTmaScores(2, 78); student2.updateTmaScores(3, 89); document.write('Scores for student1 are ' + student1.tmaScores.toString()+'<BR>'); document.write('Scores for student2 are ' + student2.tmaScores.toString()) </SCRIPT> </HEAD> <BODY> </BODY> </HTML> we need to give the constructor function an extra argument, noOfTmas, which will enable an appropriately sized array to be created by the constructor function assigns the function updateTmaResults() to the method updateTmaScores. Note that a function’s parentheses are omitted when assigning it to a method name instructs the object referenced by student1 to execute its updateTmaScores() method which in turn is simply a reference to the updateTmaResults() function, with the arguments 1 and 56 57
5- Objects in JavaScript If you want to display the scores for each student1: var myStudentScores = student1.tmaScores.toString() document.write(myStudentScores) The first line of this code means: student1 is simply the name of a variable we have chosen to reference a Student object. student1.tmaScores references the array holding the tmaScores for student1. toString() is an Array method that will convert all the elements in an array into strings and then concatenate them into a single string of comma-separated elements which is returned as the result. 58
5- Objects in JavaScript To add an additional method to the Student object type called display(), which will write out the values of all the properties for a Student object function displayStudent() { document.write('Name: ' + this.name); document.write('<BR>'); document.write('Course: ' + this.courseCode); document.write('<BR>') document.write('Student ID: ' + this.studentID); document.write('TMA Scores: ' + this.tmaScores.toString()); }; First, you need to write a function called displayStudent() to display the values of a student’s properties using document.write(). this.display = displayStudent Then, you need to add a line of code to the constructor function so as to assign your function to a method named display() student1.display(); student2.display() Finally, you need to call the display() method for student object 59
5- Objects in JavaScript Modify the program, to add another method to the Student object type called displayTmaAverage(). This will be used to calculate and display a student’s average TMA score function displayAverageScore() // the new function we asked you to write { var total = 0; var average; for (var index = 0; index < this.tmaScores.length; index=index+1) total = total + this.tmaScores [index] }; average = total / this.tmaScores.length; document.write ('TMA average for ' + this.name+':' + average +'<BR>') }; Please see the final solution in the file Solution_9.5.6 60
5- Objects in JavaScript Object types and .js files In constructing our Student object type we placed all the code in the same file as the main program that created and manipulated particular student instances. Also we can put our Student constructor function, and the related functions which are assigned to methods, into a self contained .js file. The code for the Student object type could then be imported (just like a function library) into any program that needed to create and use Student objects. Please see the solution in the file Solution_9.5.7 61