Download presentation
Presentation is loading. Please wait.
1
Arab Open University - Riyadh
Outline Unit 9: Managing complexity through modularity 1- Introduction 2- Separate code modules 3- Function library 4- Programming with function libraries 5- Objects in JavaScript Arab Open University - Riyadh
2
What is a Module? A module 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 (e.g. functions, procedures), or it may be a separate file. Modular programming refers to the use of modules in developing software. In JavaScript, there are 2 kinds of modules: function libraries and object types.
3
Outline Unit 9: Managing complexity through modularity 1- Introduction
2- Separate code modules 3- Function libraries 4- Programming with function libraries 5- Objects in JavaScript
4
Separate Code Modules Disadvantages:
Old programming practice was based on writing programs as a single very big monolithic code file. Disadvantages: Very much time consuming. Risk of loosing the string of logical thinking while writing. Very error prone. Difficult to debug, modify, and update. Inability to distribute tasks among several programmers. Structuring a program into several code modules in several files helps overcome these problems.
5
Separate Code Modules Some benefits of separate code modules:
Locating and isolating problems is much easier. It allows many people to work on the same project, so shortening development time and reducing complexity of large software projects. Modules reusable and replaceable. Reusable JavaScript functions can be collected in files which can then be imported into programs as and when needed. Such a file is called a function library and it is an example of a module. A function library is a file with the extension (.js) and contains text that is JS code.
6
Outline Unit 9: Managing complexity through modularity 1- Introduction
2- Separate code modules 3- Function libraries 4- Programming with function libraries 5- Objects in JavaScript
7
Function Libraries Code reusability consists of writing a piece of code once for solving a problem and then save it for solving later similar problems. We could Copy/Paste the wanted function code from the old program into the new one, but that’s not the optimal solution. A better solution is to collect and save reusable functions into files called function libraries. The libraries are imported into the new code when functions are needed. If you import a library into your program, it is as if you copy/pasted all its functions into your code or had to rewrite them all.
8
Function Libraries Functions in a function library must be documented precisely. We need to specify: the name of the function; any arguments and their types; what the function does; the value returned, if any, and what it represents. That information forms the function specification. (See page 15 for some examples.) This use of library functions (or indeed any software module) by reference solely to the documentation rather than their implementation is sometimes called black box programming.
9
Importing function libraries in JavaScript
Example 1 <SCRIPT SRC = myLibrary.js> </SCRIPT> or <SCRIPT SRC = myLibrary.js> </SCRIPT> Example 2 <SCRIPT SRC = C:\M150\JavaScript\FunctionLibraries\myLibrary.js> </SCRIPT> Example 3 <SCRIPT SRC = </SCRIPT> Used when the function library file is in the same folder as the main program. This is the style adopted in M150.
10
Importing function libraries in JavaScript
Note that a SCRIPT tag that includes a SRC attribute cannot contain anything else. Your own code must go between a second pair of SCRIPT tags, as shown below: <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> The functions’ specifications for the drawingLibrary.js function library start on page 14 of Unit 9.
11
Outline Unit 9: Managing complexity through modularity 1- Introduction
2- Separate code modules 3- Function libraries 4- Programming with function libraries 5- Objects in JavaScript
12
Object types you met in part A: Array, String, Document, Window
The Date object type Object types you met in part A: Array, String, Document, Window The Date object belongs to the dateLibrary.js Creating a new Date object (with the current date and time): var today = new Date() The reserved word new is used to create an object (of an undetermined type) and assign it to the variable today. Date() is what is termed a constructor function, i.e. a function which is used to initialize a newly-created object into a particular kind of object type – in this case a Date. Thus, new Date() tells JavaScript what kind of object we want. When the above code executes, 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.
13
The Date object type: creation
Creating a Date object for a specific date and time: The most accurate method is: var myDate = new Date(2004,4,3,12,24,34,15) All the arguments except those for the year and month are optional. If they are left out, JavaScript will set them to 00, allowing for dates to be created with varying accuracy, as follows: var myDate = new Date(2004,4,3,12,24,34) var myDate = new Date(2004,4,3,12,24) 3 May 2004 at 12:24:00:00 var myDate = new Date(2004,4,3,12) var myDate = new Date(2004,4,3) var myDate = new Date(2004,4) 1 May 2004 at 00:00:00:00 Millisecond Year Month Day of month Hour Minute Second
14
The Date object type: creation
Pay attention to the following: Months are ordered from 0, so April, the fourth month, is represented by the number 3 The 24 hour clock is used, so 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 :45:21') Var myDate = new Date('May :45') Var myDate = new Date('May ') Note that if you use a string argument, the full month name must appear in the string first, followed by the day of the month, followed by the year and then the time.
15
The Date object type: methods
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) The following methods can be used to change (or reset) the various elements of a date: setFullYear(year), setMonth(month), setDate(day), setHours(hour), setMinutes(minute), setSeconds(second) (the day of the week cannot be set)
16
SAQ 4.2: Write a line of code which will create the date 22 November 1955 and assign it to the variable myDate. var myDate = new Date('November ') or var myDate = new Date(1955,10,22)
17
Programming with the dateLibrary.js function library
ACTIVITY 4.2 Write a program that will tell a user how old they are to the nearest day! The program will write out their age in both years and days. Prompt the user for the year, month and day of their birthday and use those values to create a date object. Create today’s date, which can be done with the code: dateToday = new Date(); 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, with some accompanying text, for example: You are 36 years old. Which means that you have been on this Earth for days. Have you used your time wisely?
18
ACTIVITY 4.2 Solution var day; var month; var year; var birthDay;
var today; year = parseFloat (window.prompt('Enter year as a four-digit number','')); month = parseFloat (window.prompt('Enter month as a number 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('<BR>'); document.write('Have you used your time wisely?')
19
Extending a function library
We’ll extend the dateLibrary.js by adding a function that creates and returns a date object based on year, month and day provided by the user. function promptForDate() /*************************************************************/ /* Function takes no arguments. Prompts user for: */ /* a year number from 1900 to */ /* a month number from 1 to */ /* a day number from 1 to */ /* Returns a Date object with the given year, month, and day */
20
function promptForDate() {
var dayNumber; var monthNumber; var yearNumber; var aDate; var days; 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','')) // create a (temporary) 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); day = parseFloat (window.prompt('Enter day number from 1 to ' + days,'')); while (dayNumber < 1 || dayNumber > days) { dayNumber = parseFloat (window.prompt('Enter day number from 1 to ' + days,'')) return new Date(yearNumber, monthNumber -1, dayNumber) }
21
Creating function libraries
A function library is simply a text file containing a collection of functions; HTML tags are not allowed or needed, the file contains pure JavaScript. Saving in the .js format from NotePad: or
22
Scope of variables Where a variable is declared in a JavaScript program affects where it can be accessed, i.e. from where in the program it can be referred to by another program statement. The extent of access to a variable is termed the scope of the variable. There are global and local variables (the next slide summarizes the differences between them).
23
In JavaScript, it is possible to declare functions inside other functions.
24
Guess the output of this program (1):
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(), the value of a is '+ a + '<BR>'); scopeTest(); document.write('After Calling scopeTest(), the value of a is ' + a + '<BR>') This is the case of a global variable being used from within a function. Before calling scopeTest(), the value of a is Inside the function, the value of a is After calling scopeTest(), the value of a is dog cat cat
25
Guess the output of this program (2):
function scopeTest2(){ // The next line of code declares a variable with scope local // to the function body. This is a different variable from the // global one defined in the main program which follows the function // definition. 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(),the value of a is ' + a + '<BR>'); scopeTest2(); document.write('After calling scopeTest2(),the value of a is ‘ + a + '<BR>'); This is the case of a global and local variable having the same name. Before calling scopeTest2(), the value of a is Inside the function, the value of a is After calling scopeTest2(), the value of a is dog cat dog
26
A note on the declaration of variables in JavaScript
JavaScript also lets you get away with not declaring variables explicitly at all – for example, you could simply 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. You should always declare your variables at the top of the relevant program or function, as the course suggests. A function’s formal argument is a variable that is local to the function. If a function declares a formal argument with the same name as a global variable declared in the outer program, the variable in the outer program becomes inaccessible to the function.
27
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. Such name collisions can cause bugs in your programs that can be difficult to track down. To limit the possibilities of name collisions, authors of JavaScript function libraries often prefix function and global variable names with the name of the function library.
28
Outline Unit 9: Managing complexity through modularity 1- Introduction
2- Separate code modules 3- Function libraries 4- Programming with function libraries 5- Objects in JavaScript
29
Primitive (basic) types
A data type defines a collection of values together with the operations that are allowable on those values. So, for example, in JavaScript 1, 27, 56 and 34 are values belonging to the number data type. Thus, 27 is a particular instance of the number data type. Examples of allowable operations for number values are +, –, *; true and false are the (only) values belonging to the Boolean data type and examples of allowable operations for such values are >, <, <=, ||, &&. Boolean and number are examples of primitive data types. Primitive data types are types that are not defined in terms of other data types, so, for example, a number is just a number, and is not made up out of, say, a Boolean and a number. Objects are the opposite to primitive data types.
30
Object types Object-oriented programming means constructing programs out of intercommunicating ‘objects’. Objects are like containers that can hold multiple values of different data types (both primitive and other object types). An object type defines the properties of its instances together with the methods that can operate on its instances. Example: 'Hello world!' is a String object or an instance of the String object type. String objects have the single property length and examples of allowable operations would be + (the concatenation operator) and the method charAt(). Because an object is like a container it can be named by a single variable.
31
Object types An object type defines a collection of properties and methods. Properties are variables, which 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. The set of values of an object’s instance variables are termed its state. Methods are the functions that act on an object’s properties and collectively implement the object’s behavior. There are three object categories in JavaScript: Native object types: are defined by the JavaScript language. Examples: 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: Window, Document, and Form object types. User-defined object types: are defined by you, the programmer.
32
Creating new object types
In order to create objects of this new Student object type we are going to need a constructor function. Here it is: function Student(aName,aCourse) { //object properties this.name = aName; this.courseCode = aCourse } var studentA = new Student('Joe','M150'); Note that we don’t need the var reserved word when declaring properties (instance variables). The this reserved word is used by JavaScript as a reference to the object that has just been created by the new reserved word.
33
Accessing properties The dot notation is used to access properties.
Important note: The dot notation cannot be used to access the properties of JavaScript’s built-in object types. For example, getMonth() and setMonth() must be used to change the month of a Date object. Exercise: Change the course code and the name of studentA (created earlier) to: ‘M255’ and ‘Jim’, respectively. studentA.courseCode = 'M255‘; studentA.name = 'Jim'
34
How objects are stored in memory
We can think of a variable as an address for a block of computer memory. If you assign a primitive data type to a variable, the variable (memory location) holds the data value. This is known as value semantics. 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, i.e. a reference to the first block of memory where the object is stored, together with the number of blocks of adjacent memory that the object occupies. This is known as reference semantics. The reason for the difference in storage mechanism stems from the fact that objects’ sizes are large and unpredictable. Contrarily, primitive types have small, fixed sizes (8 bytes).
35
How objects are stored in memory
var studentA = new Student(‘Meena’, ‘M254’, 27634); var aNumber = 99 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.
36
Primitive types and assignment
1 var a = 56; //a now holds the value 56 2 var b = a; //b now holds the value 56 3 a = 22 //a now holds the value 22, but b still holds the value 56
37
Objects and assignment
var studentA; var studentB; studentA = new Student('Meena','M254',76549); studentB = studentA; What will that states of studentA and studentB be after executing the following line? studentA.studentID = 27634; What has happened and why?
38
Adding behavior: object methods
Assume that you have the following constructor function for Student objects: function Student(aName,aCourse, idNumber,noOfTmas) { //object properties this.name = aName; this.courseCode = aCourse; this.studentID = idNumber; this.tmaScores = new Array(noOfTmas) } To add a method to the Student object type, do the following: Define the function in the usual way Add the following statement to the constructor: this.methodName = functionName; This statements assigns the function to the method name. Note that a function’s parentheses are omitted when assigning it to a method name.
39
Adding behavior: object methods
The following example will demonstrate the creation of a function called updateTmaResults() and using it to add a method, updateTmaScores(), to the Student object type. function updateTmaResults(tmaNo,score) { // arrays in JavaScript are zero based // so we deduct 1 from the TMA number this.tmaScores [tmaNo – 1] = score } function Student(aName,aCourse,idNumber,noOfTmas) { // object properties this.name = aName; …………………………… // object methods this.updateTmaScores = updateTmaResults; }
40
ACTIVITY 5.6 Add another method to the Student object type called displayTmaAverage(). This will be used to calculate and display a student’s average TMA score. (page 58) How is the average score calculated? Sum of all TMAs’ scores / number of TMAs What property of a student object will be needed? How is this property accessed from within the function definition?
41
function Student(aName,aCourse,idNumber,noOfTmas) {
// object properties this.name = aName; ……………… // object methods this.displayTmaAverage = displayAverageScore; }; // other function definitions here function displayAverageScore() // the new function { 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>') } Property of Property of
42
What’s Next? Practice Unit 9 exercises and activities Read Unit 10
Start working on TMA03
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.