User:Jesdisciple/JavaScript/Functions and Objects

From Wikibooks, open books for an open world
Jump to: navigation, search
Previous: Control Structures Index Next: Event Handling


Functions[edit]

Functions allow you to split your code up into separate parts. This commonly allows a complex task to be broken up into several simple tasks, which then become easier to manage and control. When you put your script into a function it keeps the browser from executing the script when the page loads. It contains a code that will be executed by an event or call to that function. It can be called from anywhere within a page or even in an external page. While they can be defined in both <head> and <body> sections it is commonly used in and highly recommended to be used in the <head> portion in order to have your function load before the rest of the page.

Functions are defined with function name() { code }. To call a function, use name().

Functions without arguments[edit]

Let us create a function that will perform for us the one of the most common examples when beginning programming. That of saying "Hello, World!"

function helloWorld() {
  alert("Hello, World!");
}

The above code is saying:

  • create a function called helloWorld
  • that doesn't expect any arguments
  • and perform the following statement, to alert a message

When we want to invoke this function in our HTML document, we call the function in the following manner:

helloWorld();

Let's put this together on a sample web page.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
 <head>
  <title>Some Page</title>
    <script type="text/javascript">
      function helloWorld() {
        alert("Hello World!");
      }
    </script>
  </head>
  <body>
    <p>A web page.</p>
    <script type="text/javascript">
      helloWorld();
    </script>
  </body>
</html>

Example[edit]

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
  <head>
    <script type="text/javascript">
      function displaymessage() {
        alert("Hello World!")
      }
    </script>
  </head>
  <body>
    <form>
      <input id="displayMessage" type="Button" value="Click Here!">
    </form>
    <script type="text/javascript">
      document.getElementById("displayMessage").onclick = displaymessage;
    </script>
  </body>
</html>

Since the line "alert("Hello World!")" was placed in a function it will not display until the button is clicked, in which case the alert will pop up.

Functions with arguments[edit]

Let's start with a quick example, then we will break it down.

function stepToFive(number) {
  if (number > 5) {
    number -= 1;
  }
  if (number < 5) {
    number += 1;
  }
  return number;
}

This program takes a number as an argument. If the number is larger than 5, it subtracts one. If it's smaller than five it adds one. Let's get down and dirty and look at this piece by piece.

function stepToFive(number) {

This is similar to what we've seen before. We now have number following the function name. This is where we define our arguments for later use, which is similar to defining variables, except in this case the variables are only valid inside of the function.

  if (number > 5) {

If statements. If the condition is true, execute the code inside the curly brackets.

    number -= 1;

Assuming that JavaScript is your first language, you might not know what this means. This takes one off from the variable number. You can think of it as a useful shorthand for number = number - 1;.

    number += 1;

This is similar to the last one, except that it adds one instead of subtracting it.

  return number;

This returns the value of number from the function. This will be covered in more depth later on.

Here is an example of using this in a page.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
 <head>
  <title>Some Page</title>
    <script type="text/javascript">
      function stepToFive(number) {
        if (number > 5) {
          number -= 1;
        }
        if (number < 5) {
          number += 1;
        }
        return number;
      }
    </script>
  </head>
  <body>
    <p>
      <script type="text/javascript">
        var num = stepToFive(6);
        alert(num);
      </script>
    </p>
  </body>
</html>

There are a few more things to cover here.

var num = stepToFive(6);

This is where the return statement in the function comes in handy. num here gets assigned the number 5, since that is what stepToFive will return when it's given an argument of 6.

Objects[edit]

The philosophy of object-oriented programming says that program code should be as modular as possible. Once you've written and tested a function, it should be possible to slot it into any program or script needing that kind of functionality and just expect it to work, because it's already been tried and tested on an earlier project.

The benefits of this approach are a shorter development time and easier debugging, because you're re-using program code that has already been proven. This 'black box' approach means that data goes into the Object and other data comes out of the Object, but what goes on inside it isn't something you need to concern yourself with.

An Object is a code structure that has its own private variables, and stores data that is isolated from outside interference. Only the Object itself can alter this data. The user works with the data through a set of public functions (called Methods) for accessing these private variables. It's probably most convenient to consider that an Object has its own set of functions that allows you to work with it in certain ways.

While JavaScript allows creating of objects, you will discover that access protection are not directly available in JavaScript; as such, it is possible to bypass the intent of the object-oriented programming by directly accessing fields or methods. To minimize the impact of these issues, you may want to ensure that methods are properly described and cover known situations of use - and to avoid directly accessing methods or fields that are designed to hold the internal state of the object.

Javascript provides a set of predefined Objects. For example: the document itself is an Object, with internal variables like 'title' and 'URL'.

The Date Object[edit]

Let's look at the Date Object. You can create a new object and assign it to a variable name using the new keyword:

var mydate = new Date();

The Date Object has a set of internal variables which hold the time, day, month, and year. It allows you to refer to it like a string, so you could for example pop-up the time that the variable was created. A pair of lines like this:

var myDate = new Date();
alert(myDate);

would display an alert box showing the current time and date, in universal time, like this:

Tue Jul 26 13:27:33 UTC+1200 2007

Even though it produced a string, the variable myDate is not actually one itself. An operator called typeof returns a string that indicates what type the variable is. These types are:

  • boolean
  • function
  • number
  • object
  • string
  • undefined

So the following code:

var myDate = new Date();
alert(typeof myDate);

would produce:

object

The Date Object stores a lot of information about the date, which are accessed using a certain predefined method. Some examples of these methods are:

  • getFullYear()
  • getMonth()
  • getDate()
  • getDay()
  • getHours()
  • getMinutes()
  • getSeconds()

The following code shows the year and what type of object that information is.

var myDate = new Date();
var year = myDate.getFullYear();
alert(year + '\n' + typeof(year));

2007
number

Because information such as the year are private to the object, the only way we have to alter that information is to use a method provided by the Object for that purpose.

The above methods to get information from the Date object have matching methods that allow you to set them too.

  • setFullYear()
  • setMonth()
  • setDate()
  • setDay()
  • setHours()
  • setMinutes()
  • setSeconds()

The following code will show one year, followed by a different year.

var myDate = new Date();
alert(myDate.getFullYear());
myDate.setFullYear(2008);
alert(myDate.getFullYear());
2007
2008

Defining New Classes[edit]

Example:

var site = {};
site.test = function (string) {
    alert("Hello World! " + string);
    site.string = string;
}
site.test("Boo!");
alert(site.string);

What this example does is:

  • Define site as an empty object
  • Add a method called test to the site object
  • Call the test method with variable "Boo!"

The result is:

  • An alert message with "Hello World! Boo!"
  • site.string being defined as string
  • An alert message with "Boo!".

In summary[edit]

An object is a structure of variables and some functions used to work with those variables. These include private variables, which can (or in JavaScript's case, should) only be referenced or changed using the methods it provides. If a Date object's getFullYear() method returns an incorrect value, you can depend on the fact that somewhere in your script, the setFullYear() method has been used to alter it.

this keyword[edit]

The this keyword allows a method to read and write the property variables of that instance of the object.

The following example uses an initial capital letter for PopMachine() to help indicate that the object needs to be created with the new keyword.

function PopMachine() {
    this.quarters = 0;
    this.dollars = 0;
    this.totalValue = function () {
        var sum = this.quarters * 25 + this.dollars * 100;
        return sum;
    }
    this.addQuarters = function (increment) {
        this.quarters += increment;
    }
    this.addDollars = function (increment) {
        this.dollars += increment;
    }
}
function testPopMachine() {
    var popMachine = new PopMachine();
    popMachine.addQuarters(8);
    popMachine.addDollars(1);
    popMachine.addQuarters(-1);
    alert("Total in the cash register is: " + popMachine.totalValue());
}
testPopMachine();

Exceptions[edit]

In Javascript, errors are created by the Error object and its subclasses. To catch the error to prevent it from stopping your script, you need to enclose sections of your code with the try...catch block.

Errors have two important fields: Error.name - which is the name of the error, and Error.message - a human readable description of the error.

While you can throw any object you want as an exception, it's strongly recommended to throw an instance of the Error object.

Further reading[edit]


Previous: Control Structures Index Next: Event Handling