Ajax, JavaScript and PHP by ygq15756


									Ajax, JavaScript and PHP

    Chapter 7 – Functions
Chapter 9 – Built-In 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
• Functions often use these arguments to compute a return
  value that becomes the value of the function invocation
• 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.
             What is a function?
• A function is a block of predefined programming
  statements whose execution is deferred until the
  function is “called”.
• You call a function by invoking its name, along with any
  required or optional parameters.
• Function parameters/arguments are data values or
  data references that you pass to a function.
• The function then uses and/or modifies those data
  values or references during its execution.
                Types of functions
• Predefined functions: predefined by the JS language but not
  associated with any particular object. parseInt(), isNaN()
• Predefined methods: predefined by the JS and associated with
  objects that have also been predefined by the language.
  window.open(), document.write()
• User-defined functions (really user-defined window methods):
  defined by a programmer. However, when a programmer declare
  a function in JS, it is actually defining a method of the window
  object. helloWorld(), greetVisitor()
• User-defined methods: defined by a programmer and associated
  with a particular object, usually a user-defined object.
     The best function-programming
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.
        Defining a function without
• function functionName() {
• }
• function helloWorld() {
   document.write(“Hello, world!”);
• }
• 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 <head> of the HTML
        Calling a simple function
• To call a function that has no parameters, simply
  invoke its name:
• You can call helloWorld by invoking its name:
• If your function will execute any document.write
  statements, then it must be called within the <body>
  of an HTML document.
   Defining and calling a function with
• The proper syntax for declaring a function with one or more
       function functionName(param1, param2, …) ,
• Let’s declare a greetByName function that will accept
  visitorName as a parameter:
        function greetByName(visitorName) {
                alert(“Hello, “ + visitorName + “!”);
• To see it it works, let’s call it.
               Function with parameter
•   <html>
•   <head><title>Function with Parameter</title>
•   <script language="JavaScript" type="text/javascript">
•   <!--
•   function greetByName(visitorName) {
•            alert("Hello, " + visitorName + "!");
•   }
•   // -->
•   </script>
•   </head>
•   <body>
•   <h1>Function with Parameter(s)</h1>
•   <script language="JavaScript" type="text/javascript">
•   <!--
•   var visitor = prompt("What\'s your name?", "");
•   greetByName(visitor);
•   // -->
•   </script>
•   </body>
•   </html>
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.
 Passing by reference (composite data
• 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.
                           Passing by reference
•   <html>
•   <head><title>Function passing by reference</title>
•   <script language="JavaScript" type="text/javascript">
•   <!--
•   function arrayData(drinks) {
•              drinks[0] = "Lemonade";
•              drinks[1] = "Iced tea";
•              drinks[2] = "Pepsi";
•              drinks[3] = "Dr. Pepper";
•   }
•   // -->
•   </script>
•   </head>
•   <body>
•   <h1>Function with Parameter(s) by reference</h1>
•   <script language="JavaScript" type="text/javascript">
•   <!--
•   var myCups = new Array();
•   document.write("Content of myCups: ", myCups, "<br>");
•   arrayData(myCups);
•   document.write("Content after function call: ", myCups, "<br>");

•   // -->
•   </script>
•   </body>
•   </html>
 Declaring a function to 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, …) ,
       return someValue;
    Declaring function to return a value
•   <html>
•   <head><title>Function with return</title>
•   <script language="JavaScript" type="text/javascript">
•   <!--
•   function getMax(num1, num2) {
•              if (num1 > num2) {
•                             return num1;
•              } else {
•                             return num2;
•              }
•   }
•   // -->
•   </script>
•   </head>
•   <body>
•   <h1>Function with return</h1>
•   <script language="JavaScript" type="text/javascript">
•   <!--
•   document.write("Max of 8 and 15 is ", getMax(8, 15), "<br>");
•   document.write("Max of -9 and 17 is ", getMax(-9, 17), "<br>");
•   document.write("Max of 8 and 8 is ", getMax(8, 8), "<br>");
•   document.write("Max of 1.1 and 1 is ", getMax(1.1, 1), "<br>");
•   // -->
•   </script>
•   </body>
•   </html>
    Defining and Invoking Functions
•   The most common way to define a function is with the function statement.
•   This function consists of the function keyword followed by:
      The name of the function
      Zero or more parameter names contained within parenthesis, each separated by
      The JavaScript statements that comprise the body of the function, contained within
         curly braces
           function print(msg) {
                       document.write(msg + “<br>”);
           function factorial(x) {
                       if (x <= 1)
                          return 1;
                       return x * factorial(x – 1);
•   Once a function has been defined, it may be invoked with the () operator.
•   The parentheses appear after the name of the function and that an optional comma-
    separated list of argument values or expressions appears within the parentheses:
         print(“Hello, “ + name);
         print(“Welcome to my web”);
         print(“The probability of that is: “ + factorial(5)/factorial(13));
                  Nested Functions
• In JavaScript, functions may be nested within other functions:
      function hypotenuse(a, b) {
        function square(x) { return x * x; }
        return Math.sqrt(square(a) + square(b));
• Nested functions may be defined only at the top level of the
  function within which they are nested (i.e. they may not be
  defined within statement blocks, or while loop)(this
  restriction applies only to functions defined with the function
• Function literal expression may appear anywhere.
                        Function Literals
• 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 f(x) { return x * x; } // function statement
       var f = function(x) { return x * x; };    // function literal
• Function literals create unnamed functions which is useful when writing
  recursive functions that call themselves:
       var f = function fact(x) { if (x <= 1) return 1; else return x * fact(x – 1); };
• Function literal expression can be stored into a variable, passed to another
  function, or even invoked directly:
       f[0] = function(x) { return x * x; }; // define a function and store it
       a.sort(function(a,b) {return a – b;}); // define a function, pass it to another
       var tensquared = (function(x) {return x * x;})(10); // define and invoke
             Naming Functions
• Any legal JavaScript identifier can be a function
• When a name includes multiple words, one
  convention is to separate words with underscores
• 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
          Function Arguments
• JavaScript functions can be invoked with any
  number of arguments, regardless of the
  number of arguments named in the function
• Function is loosely typed, it is legal to pass
  values of any type to any function
                  Optional Arguments
•   When a function is invoked with fewer arguments than are declared, the
    additional arguments have the undefined value.
•   It is often useful to write functions so that some arguments are optional and may
    be omitted when the function is invoked:
          // append the names of the enumerable properties of object
          // o to the array a, and return a. If a is omitted or null, create
          // and return a new array.
          function copyPropertyNamesToArray(o, /* optional */ a) {
            if (!a) a = [ ];     // if undefined or null, use a blank array
            for (var property in o) a.push(property);
            return a;
•   With the function defined this way, you have flexibility in how it is invoked:
          // get property names of objects o and p
          var a = copyPropertyNamesToArray(o);
    Variable-Length Argument Lists: The
              Argument Object
•   Within the body of a function, the identifier arguments has special meaning.
•   Arguments is a special property that refers to an object known as the Arguments
•   The Arguments object is an array-like object that allows the argument values
    passed to the function to be retrieved by number, rather than by name.
•   The Arguments object also defines an additional “callee” property.
•   Although a JavaScript function is defined with a fixed number of named
    arguments, it can be passed any number of arguments when it is invoked.
•   The Arguments object allows full access to these argument values, even when
    some of all are unnamed (argument*0+, argument*1+, etc…):
        function f(x, y, z) {
          if (arguments.length != 3) {
                     throw new Error(“function f called with “ + arguments.length +
                              “arguments, but it expects 3 arguments.”);
        // actual function…
  Variable-Length Argument Lists: The
            Argument Object
• The arguments object also open up an important possibility
  for JavaScript functions: they can be written so that they work
  with any number of arguments:
      function max(/*… */) ,
        var m = Number.NEGATIVE_INFINITY;
        for (var i = 0; i < arguments.length; i++)
                   if (arguments[i] > m) m = arguments[i];
        return m;
• Functions like this one that can accept any number of
  arguments are called “variadic functions”, variable arity
  functions, or varargs functions.
              The callee Property
• The Arguments object defines a callee property that
  refers to the function that is currently being
• This property is rarely useful, but it can be used to
  allow unnamed functions to invoke themselves
     function(x) {
       if (x <= 1) return 1;
       return x * arguments.callee(x – 1);
                  Argument Types
• Since JavaScript is loosely typed, method arguments have no
  declared types, and no type checking is performed on the
  values you pass to a function.
• You can self-documenting by including argument types in
• For arguments that are optional, you can include the word
  “optional” in the comment
• When a method can accept any number of arguments, you
  can use an ellipsis.
• If you write a function that expects a string argument and
  then call that function with a value of some other type, the
  value you passed will simply be converted to a string when
  the function tries to use it as a string.
• All primitive types can be converted to strings, and all objects
  have toString() methods.
                        Functions as Data
•   In JavaScript, functions are not only syntax but also data, they can be assigned to
    variables, stored in the properties of objects or the elements of arrays, passed as
    arguments to functions, and so on…
        function square(x) { return x * x; }
•   This definition creates a new function object and assigns it to the variable square.
    The function can be assigned to another variable:
        var a = square(4);        // a contains square of 4
        var b = square;                       // b refers to function square
        var c = b(5);             // c contains result of square 5
•   Functions can also be assigned to object properties:
        var o = new Object;
        o.square = function(x) { return x * x; }         // function literal
        y = o.square(3);         // y contains result of square 3
•   Functions can also be assigned to array elements:
        var a = new Array(3);
        a[0] = function(x) { return x * x; }
        a[1] = 5;
        a[2] = a[0](a[1]);       // a[2] contains result of square 5
                  Functions as Methods
•   A method is nothing more than a JavaScript function that is stored in a property of an object
    and invoked through that object.
•   If you have a function f and an object o, you can define a method name m:
         o.m = f;
•   Having defined the method m() of the object o, invoke it like this:
         o.m(x, x+2); // if m() requires two arguments
•   Methods have one very important property: the object through which a method is invoked
    becomes the value of the this keyword within the body of the method.
•   Thus, when you invoke o.m(), the body of the method can refer to the object o with the this
         var calculator = {                    // an object literal
            operand1: 1,
            operand2: 2,
            compute: function() {
                       this.result = this.operand1 + this.operand2;
         alert(calculator.result); // display the result
         Constructor Functions
• A constructor function is a function that
  initializes the properties of an object and is
  intended for use with the new operator.
  Functions Properties and Methods
• The typeof operator returns the string
  “function” when applied to a function, but
  functions are really a specialized kind of
  JavaScript object.
• Since functions are objects, they have
  properties and methods.
                 The length Property
• The length property of the arguments array specifies the number of
  arguments that were passed to the function. (arguments.length)
• The length property of a function itself, is a read-only property, returns the
  number of arguments that the function expects to be passed – that is, the
  number of parameters it declares in its parameter list.
      function check(args) {
        var actual = args.length;     // actual number of arguments
        var expected = args.callee.length; // expected number of arguments
        if (actual != expected) {
                  throw new Error(“Wrong number of arguments: expected: “
      + expected + “; actual passed “ + actual);
Creating Libraries in External JavaScript
• A function definition can be placed in an external JS
  file and linked into a document with a script tag in
  the <head> of the HTML document.
• Place a bunch of regularly used function definitions
  in one external JS file and you are got yourself a
• A library is a group of reusable function definitions,
  usually related to each other in some way.
                HTML with external JS file
•   <html>
•   <head><title>Function with external file</title>
•   <script language="JavaScript" type="text/javascript">
•   <!--
•   function greetByName(visitorName) {
•              alert("Hello, " + visitorName + "!");
•   }
•   // -->
•   </script>
•   <script src="myscript.js">
•   </script>
•   </head>
•   <body>
•   <h1>Function with external file</h1>
•   <script language="JavaScript" type="text/javascript">
•   <!--
•   var visitor = prompt("What\'s your name?", "");
•   greetByName(visitor);
•   document.write("Max of 8 and 15 is ", getMax(8, 15), "<br>");
•   document.write("Max of -9 and 17 is ", getMax(-9, 17), "<br>");
•   document.write("Max of 8 and 8 is ", getMax(8, 8), "<br>");
•   document.write("Max of 1.1 and 1 is ", getMax(1.1, 1), "<br>");
•   // -->
•   </script>
•   </body>
•   </html>
             External JS file
• function getMax(num1, num2) {
•    if (num1 > num2) {
•          return num1;
•    } else {
•          return num2;
•    }
• }
    setTimeout() and setInterval()
• window has two common methods setTimeout() and
• 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 JS statement
  or function after a certain period of time.
• setTimeout(“statement”, numMilliseconds);
• setTimeout(“functionName()”, numMilliseconds);
    setTimeout() and clearTimeout()
•   <html>
•   <head><title>Function with setTimout</title>
•   <script language="JavaScript" type="text/javascript">
•   <!--
•   var reminder;
•   function displayAlert() {
•              alert("5 seconds have elapsed.");
•   }
•   function callTimer() {
•              reminder = setTimeout("displayAlert()", 5000);
•   }
•   // -->
•   </script>
•   </head>
•   <body>
•   <h1>Function with setTimeout</h1>
•   <form>
•   <p>Click the button on the left for a reminder in 5 seconds; click the button
•   on th right to cancel the reminder before it is displayed. </P>
•   <input type="button" value="Set 5-Second Reminder"
•   onClick = "callTimer()">
•   <input type="button" value="Clear Reminder" onClick="clearTimeout(reminder)">
•   </form>

•   </body>
•   </html>
  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.
• timerName = setTimeout(“functionName”,
• clearTimeout(timerName);
   setInterval() and clearInterval()
• 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”,
• Syntax for saving an interval’s unique ID:
   – timerName = setInterval(“functionName”,
• Syntax for using clearInterval():
   – clearInterval(timerName);
      setInterval() and clearInterval()
•   <html>
•   <head><title>Function with setInterval</title>
•   <script language="JavaScript" type="text/javascript">
•   <!--
•   var reminder;
•   function displayAlert() {
•              alert("5 seconds have elapsed.");
•   }
•   function callTimer() {
•              reminder = setInterval("displayAlert()", 5000);
•   }
•   // -->
•   </script>
•   </head>
•   <body>
•   <h1>Function with setInterval</h1>
•   <form>
•   <p>Click the button on the left for a repeated reminder every 5 seconds; click the button
•   on th right to cancel the reminder before it is displayed. </P>
•   <input type="button" value="Set Repeating 5-Second Reminder"
•   onClick = "callTimer()">
•   <input type="button" value="Clear Reminder" onClick="clearInterval(reminder)">
•   </form>

•   </body>
•   </html>
                  Using setInterval to create an
                      automatic slideshow
•   <html>
•   <head><title>Function with setInterval slideshow</title>
•   <script language="JavaScript" type="text/javascript">
•   <!--
•   var currentSlide = 0;
•   if (document.images) {
•   // test if images object exist. if images are supported by the browser, create an array of images and preload them.
•   var slides = new Array();
•                 slides[0] = new Image();
•                 slides[0].src = "0_happi.jpg";
•                 slides[1] = new Image();
•                 slides[1].src = "1_happi.jpg";
•                 slides[2] = new Image();
•                 slides[2].src = "2_happi.jpg";
•                 slides[3] = new Image();
•                 slides[3].src = "3_happi.jpg";
•                 slides[4] = new Image();
•                 slides[4].src = "4_happi.jpg";
•                 slides[5] = new Image();
•                 slides[5].src = "5_happi.jpg";
•   }
•   function nextImage() {
•                 if (document.images && document.slideshow.complete) {
•                 // if browser support images, and image loaded complete
•                                       if (currentSlide == slides.length) {
•                                                             currentSlide = 0;
•                                       }
•                                       document.slideshow.src = slides[currentSlide].src;
•                                       currentSlide++;
•                 }
•   }
                Using setInterval to create an
                    automatic slideshow
•   function stopSlide() {
•              clearInterval(mySlideShow);
•   }
•   // -->
•   </script>
•   </head>
•   <body>
•   <h1>Function with setInterval slideshow</h1>
•   <form>
•   <table align="center" border="2">
•   <tr><td><img src="0_happi.jpg" name="slideshow" width="200" height="180" alt="My slideshow"></td></tr>
•   <tr><td align="center">
•   <input type="button" value="Stop Slideshow"
•   onClick = "stopSlide()"></td></tr>
•   </table>
•   </form>
•   <script language="JavaScript" type="text/javascript">
•   <!--
•   var mySlideShow = setInterval("nextImage()", 2000);

•   // -->
•   </script>
•   </body>
•   </html>
   Built-In function – Math Object
• The Math object is a built-in JS 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.
Generating random number from 1 to
• You will usually want a random number between one
  and a value.
• You can do this with a general-purpose random
  number function.
• The following is a function that generates random
  numbers between one and the parameter you send
  function rand(num) {
    return Math.floor(Math.random() * num) + 1;
            Creating a Date object
• The Date object is a built-in JS object that enables you to
  conveniently work with dates and times.
• You can create a Date object anytime you need to store a
  date, and use the Date object’s methods to work with the
• You can create a Date object using the new keyword.
• You can also optionally specify the date to store in the object
  when you create it.
• You can also use any of the following formats:
   birthday = new Date();
   birthday = new Date(“June 20, 2009 08:00:00”);
   birthday = new Date(6, 20, 2009);
   birthday = new Date(6, 20, 2009, 8, 0, 0);
              Setting Date values
• A variety of set methods enable you to set
  components of a Date object to values:
    setDate(): sets the day of the month.
    setMonth(): sets the month. JS numbers the months from
     0 to 11, starting with January (0).
    setFullYear(): sets the year.
    setTime(): sets the time (and the date) by specifying the
     number of milliseconds since January 1, 1970.
    setHours(), setMinutes(), and setSeconds() set the time.
             Reading Date values
• You can use the get methods to get values from a
  Date object. This is the only way to obtain these
  values, because they are not available as properties.
    getDate(): gets the day of the month.
    getMonth(): gets the month.
    getFullYear(): gets the year.
    getTime(): gets the time (and the date) as the number of
     milliseconds since January 1, 1970.
    getHours(), getMinutes(), getSeconds(), and
     getMilliseconds() get the components of the time.
           Working with Time Zones
• getTimeZoneOffset(): gives you the local time zone’s offset from UTC time.
• toUTCString(): converts the date object’s time value to text, using UTC.
• toLocalString(): converts the date object’s time value to text, using local
• getUTCDate(): gives the day of the month in UTC time.
• getUTCDay(): gives the day of the week in UTC time.
• getUTCFullYear(): gets the four-digit year in UTC time.
• getUTCMonth(): returns the month of the year in UTC time.
• getUTCHours(), getUTCMintues(), getUTCSeconds(), and
  getUTCMilliseconds(), return the components of the time in UTC.
• setUTCDate(), setUTCFullYear(), setUTCMonth(), setUTCHours(),
  setUTCMintues(), setUTCSeconds(), and setUTCMilliseconds() set the time
  in UTC.
   Converting between Date formats
• Two special methods of the Date object allow you to
  convert between date formats.
• Instead of using these methods with a Date object
  you created, you use them with the built-in object
  Date itself.
    Date.parse(): converts a date string, suchas as June 20,
     1996, to a Date object (number of milliseconds since
    Date.UTC(): does the opposite. It converts a Date object
     value (number of milliseconds) to a UTC (GMT) time.
      Using third-party libraries
• Dojo (http://www.dojotoolkit.org/)
• The yahoo! UI library
• Mochikit (http://mochikit.com/)

To top