Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript and Ajax (JavaScript Functions) Week 5 Web site:

Similar presentations


Presentation on theme: "JavaScript and Ajax (JavaScript Functions) Week 5 Web site:"— Presentation transcript:

1 JavaScript and Ajax (JavaScript Functions) Week 5 Web site: http://fog.ccsf.edu/~hyip

2 Functions A function is a block of JavaScript code that is defined once but may be invoked, or executed, any number of times. Functions may have parameters, or arguments – local variables whose value is specified when the function is invoked. Functions often use these arguments to compute a return value that becomes the value of the function invocation expression. When a function is invoked on an object, the function is called a method, and the object on which it is invoked is passed as an implicit argument of the function.

3 Types of Functions 1.Predefined functions: predefined by the JavaScript language but not associated with any particular object. [parseInt(), isNaN()] 2.Predefined methods: predefined by the JavaScript and associated with objects that have also been predefined by the language. [window.open(), document.write()] 3.User-defined functions (really user-defined window methods): defined by a programmer. However, when a programmer declare a function in JavaScript, it is actually defining a method of the window object. [helloWorld(), greetVisitor()] 4.User-defined methods: defined by a programmer and associated with a particular object, usually a user-defined object. [pen.write()]

4 The best function-programming practices 1.A well-written function performs one task and one task alone. 2.A well-written function stands on its own and causes no side effects to variables or objects outside its scope. 3.A well-written function is well documented with comments, including what the function does, what input it requires, and what output, if any, it returns.

5 (1) Functions Without Parameters A function definition needs to be placed such that the function gets defined and read into memory before it is called to work So, always declare them in the of the HTML document. function functionName() { Statements; } function helloWorld() { document.write("Hello, world!"); }

6 Calling a Simple Function To call a function that has no parameters, simply invoke its name: functionName(); You can call helloWorld by invoking its name: helloWorld(); If your function will execute any document.write statements, then it must be called within the of an HTML document.

7 (2) Functions With Parameters The proper syntax for declaring a function with one or more parameters function functionName(param1, param2, …) { statements; } Let’s declare a greetByName function that will accept visitorName as a parameter: function greetByName(visitorName) { alert("Hello, " + visitorName + "!"); } To see if it works, let’s call it. greetByName("Sam"); greetByName("Davan");

8 (a) Passing by value (primitive data types) Whenever primitive data types (number, string, Boolean) are used as arguments to function calls, those arguments are passed by value, that is, the function receives the actual value of the argument and stores that value in its parameter variable. The value of the variable used as an argument remains unchanged by the function call.

9 (b) Passing by reference (composite data types) Whenever you pass composite data types such as objects/arrays as arguments to a function, you pass the actual object itself. The parameter name becomes another reference to the object passed; that is, the parameter name becomes another name by which the object can be referred to. Anything you do to the parameter in the function affects the original object.

10 Pass by Reference Sample function arrayData(drinks) { drinks[0] = "Lemonade"; drinks[1] = "Iced tea"; drinks[2] = "Pepsi"; drinks[3] = "Dr. Pepper"; } var myCups = new Array(); document.write("Content of myCups: ", myCups, " "); arrayData(myCups); document.write("Content after function call: ", myCups, " ");

11 (3) Functions Return a Value If a function needs to return a value, you need to include a return statement in your function, usually as the last line. A function can have more than one return statement, each defined for a particular condition, but only one return statement can execute and only one value or object can be returned. function functionName(param1, param2, …) { statements; return someValue; }

12 Function Return a Value Sample function getMax(num1, num2) { if (num1 > num2) { return num1; } else { return num2; } document.write("Max of 8 and 15 is ", getMax(8, 15), " "); document.write("Max of -9 and 17 is ", getMax(-9, 17), " "); document.write("Max of 8 and 8 is ", getMax(8, 8), " "); document.write("Max of 1.1 and 1 is ", getMax(1.1, 1), " ");

13 Defining and Invoking Functions There are two ways to define JavaScript functions: 1.The most common way to define a function is with the function statement. function f(x) { return x * x; } function factorial(x) { if (x <= 1) { return 1; } return x * factorial(x – 1); } var a = f(2); var b = factorial(3);

14 Defining and Invoking Functions (continue…) 2.JavaScript allows functions to be defined with function literals. A function literal is an expression that defines an unnamed function. The syntax for a function literal is much like that of the function statement, except that it is used as an expression rather than as a statement and no function name is required. Function literals create unnamed functions which is useful when writing recursive functions that call themselves. Var f1 = function(x) { return x * x; };// function literal var f2 = function(x) { if (x <= 1) return 1; else return x * f2(x – 1); }; var a = f1(2); var b = f2(3);

15 Naming Functions Any legal JavaScript identifier can be a function name. When a name includes multiple words, one convention is to separate words with underscores like_this(); Another convention is to begin all words after the first with an uppercase letter likeThis(). Functions that are supposed to be internal or hidden are sometimes given names that begin with an underscore.

16 Creating Libraries in External JavaScript files A function definition can be placed in an external JavaScript file and linked into a document with a script tag in the of the HTML document. Place a bunch of regularly used function definitions in one external JavaScript file and you are got yourself a library. A library is a group of reusable function definitions, usually related to each other in some way.

17 HTML with external JS file Function with external file document.write("Max of 8 and 15 is ", getMax(8, 15), " "); document.write("Max of -9 and 17 is ", getMax(-9, 17), " "); document.write("Max of 8 and 8 is ", getMax(8, 8), " "); document.write("Max of 1.1 and 1 is ", getMax(1.1, 1), " ");

18 Content of the external file – myscript.js function getMax(num1, num2) { if (num1 > num2) { return num1; } else { return num2; }

19 JavaScript built-in functions window has two common methods setTimeout() and setInterval(). The window method setTimeout lets you call a function after a specified number of milliseconds have elapsed. It allows you to set a timer that calls a JavaScript statement or function after a certain period of time. setTimeout("statement", numMilliseconds); setTimeout("functionName()", numMilliseconds);

20 Built-in function – setTimeout() var reminder; function displayAlert() { alert("5 seconds have elapsed."); } function callTimer() { reminder = setTimeout("displayAlert()", 5000); } Click the button on the left for a reminder in 5 seconds; click the button on the right to cancel the reminder before it is displayed.

21 setTimeout() and clearTimeout() The setTimeout() will return an integer representing the timeout’s unique identification. By assigning the returned ID to a variable, you can control the time-out, stopping it if necessary. If you don’t assign the value returned by setTimeout to a variable when it is called, you will have no way to identify the time-out so you can tell it to stop. var timerName = setTimeout("functionName()", numMilliseconds); clearTimeout(timerName);

22 setInterval() and clearInterval() var reminder; function displayAlert() { alert("5 seconds have elapsed."); } function callTimer() { reminder = setInterval("displayAlert()", 5000); } Click the button on the left for a repeated reminder every 5 seconds; click the button on the right to cancel the reminder before it is displayed.

23 setInterval() and clearInterval() (continue…) The window method, setInterval differs from its cousin and predecessor setTimeout in that it repeatedly calls a statement or function every so many milliseconds. setInterval("statement/functionName", numMilliseconds); Syntax for saving an interval’s unique ID: var timerName = setInterval("functionName()", numMilliseconds); Syntax for using clearInterval(): clearInterval(timerName);

24 Built-in function – Math Object The Math object is a built-in JavaScript object that includes math constants and functions.  Math.ceil(): rounds a number up to the next integer.  Math.floor(): rounds a number down to the next integer.  Math.round(): rounds a number to the nearest integer.  Math.sin(): calculate sines.  Math.cos(): calculate cosines.  Math.PI: is a property, Mathematical constants PI.  Math.random(): generate a random decimal number between zero and one.


Download ppt "JavaScript and Ajax (JavaScript Functions) Week 5 Web site:"

Similar presentations


Ads by Google