Arab Open University - Riyadh

Slides:



Advertisements
Similar presentations
Introducing JavaScript
Advertisements

The Web Warrior Guide to Web Design Technologies
JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
JavaScript 101 Lesson 01: Writing Your First JavaScript.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
XP 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial 10.
CIS101 Introduction to Computing Week 11. Agenda Your questions Copy and Paste Assignment Practice Test JavaScript: Functions and Selection Lesson 06,
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Functions Part I.
Guide To UNIX Using Linux Third Edition
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Lesson15. JavaScript Objects Objects encapsulate data (properties) and behavior(methods); the properties and the methods of an object are tied together.
Using Data Active Server Pages Objectives In this chapter, you will: Learn about variables and constants Explore application and session variables Learn.
Functions and Objects. First Midterm exam Date: October 8, 2008 Content: Two parts: On-paper:Multiple choices On-computer: Write codes Cover everything.
JavaScript, Fourth Edition
Computers and Scientific Thinking David Reed, Creighton University Functions and Libraries 1.
WDMD 170 – UW Stevens Point 1 WDMD 170 Internet Languages eLesson: Variables, Functions and Events (there is an audio component to this eLesson) © Dr.
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
Dr. Qusai Abuein1 Internet & WWW How to program Chap.(6) JavaScript:Introduction to Scripting.
Chapter 2: Variables, Functions, Objects, and Events JavaScript - Introductory.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
JavaScript Introduction and Background. 2 Web languages Three formal languages HTML JavaScript CSS Three different tasks Document description Client-side.
1 CSC160 Chapter 1: Introduction to JavaScript Chapter 2: Placing JavaScript in an HTML File.
JavaScript 101 Lesson 6: Introduction to Functions.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
ITM 3521 ITM 352 Functions. ITM 3522 Functions  A function is a named block of code (i.e. within {}'s) that performs a specific set of statements  It.
What is an object?. What Makes an Object? An object has identity (it acts as a single whole). Every object has a name that identifies what it is. Ex.
© 2010 Robert K. Moniot1 Chapter 6 Introduction to JavaScript.
JavaScript Part 1 Introduction to scripting The ‘alert’ function.
JavaScript: Conditionals contd.
Module 1 Introduction to JavaScript
CST 1101 Problem Solving Using Computers
Creating and Using Objects, Exceptions, Strings
User-Written Functions
Chapter 6 JavaScript: Introduction to Scripting
Programming Logic and Design Seventh Edition
Learning to Program D is for Digital.
Chapter 4 Client-Side Programming: the JavaScript Language
JavaScript: Functions
M150: Data, Computing and Information
Scope, Objects, Strings, Numbers
Introduction to Scripting
JavaScript Syntax and Semantics
JavaScript: Functions.
The structure of computer programs
User-Defined Functions
JavaScript an introduction.
VISUAL BASIC.
BY: SITI NURBAYA ISMAIL FACULTY of COMPUTER and MATHEMATICAL SCIENCES
Chapter 3 Introduction to Classes, Objects Methods and Strings
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
Variables Title slide variables.
M150: Data, Computing and Information
An Introduction to JavaScript
JavaScript CS 4640 Programming Languages for Web Applications
Data Structures & Algorithms
Introducing JavaScript
An Introduction to JavaScript
Introduction to Programming and JavaScript
JavaScript: Introduction to Scripting
Classes, Objects and Methods
Web Programming and Design
ITM 352 Functions.
Classes and Objects Object Creation
 A function is a named sequence of statement(s) that performs a computation. It contains  line of code(s) that are executed sequentially from top.
Intro to Programming (in JavaScript)
JavaScript CS 4640 Programming Languages for Web Applications
CMSC 202 Constructors Version 9/10.
Chapter 5 JavaScript Numbers and Expressions
Presentation transcript:

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

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.

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

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.

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.

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

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.

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.

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 = http:/www.somewhere.co.uk/exampleJSCode/myLibrary.js> </SCRIPT> Used when the function library file is in the same folder as the main program. This is the style adopted in M150.

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.

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

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.

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

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 3 2004 11:45:21') Var myDate = new Date('May 3 2004 11:45') Var myDate = new Date('May 3 2004') 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.

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)

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 22 1955') or var myDate = new Date(1955,10,22)

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 13149 days. Have you used your time wisely?

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?')

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 3000 */ /* a month number from 1 to 12 */ /* a day number from 1 to 31 */ /* Returns a Date object with the given year, month, and day */

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) }

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

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).

In JavaScript, it is possible to declare functions inside other functions.

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

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

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.

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.

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

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.

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.

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.

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.

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'

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).

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.

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 1 2 3

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?

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.

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; }

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?

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

What’s Next? Practice Unit 9 exercises and activities Read Unit 10 Start working on TMA03