JavaScript/Functions and Objects


Previous: Control Structures Index Next: Event Handling

FunctionsEdit

A function is an action to take to complete a goal, objective, or task. Functions allow you to split a complex goal into simpler tasks, which make managing and maintaining scripts easier. A parameter or argument is data which is passed to a function to effect the action to be taken. Functions can be passed zero or more arguments. A function is executed when a call to that function is made anywhere within the script, the page, an external page, or by an event. Functions are always guaranteed to return some value when executed. The data passed to a function when executed is known as the function's input and the value returned from an executed function is known as the function's output.

Functions can be constructed in three main ways. We begin with three "Hello, World!" examples:

Way 1 Way 2 Way 3
function hello() {
  alert("Hello, World!");
}
var hello = function() {
  alert("Hello, World!");
};
var hello = new Function(
  'alert("Hello, World!");'
);

Each function:

  • can be called with hello()
  • does not expect any arguments
  • performs an action to alert the user with a message
  • undefined is returned when execution is finished

The hello function can be changed to allow you to say hello to someone specific through the use of arguments:

Way 1 Way 2 Way 3
function hello(who) {
  alert("Hello, " + who + "!");
}
var hello = function(who) {
  alert("Hello, " + who + "!");
};
var hello = new Function('who',
  'alert("Hello, " + who + "!");'
);

Each function:

  • can be called with hello
  • expects one argument to be passed
  • performs an action to alert the user with a message
  • undefined is returned when execution is finished

Each function can be called in several ways:

Way 1 Way 2 Way 3
hello("you");
hello.call(window, "you");
hello.apply(window, ["you"]);

Let's put this together on a sample web page. Call the function once when the page is loaded. Call the function again whenever a button is clicked.

<html>
 <head><title>Some Page</title></head>
 <body>
  <button id="msg">greeting</button>
  <script type="text/javascript">
   function hello() {
     alert("Hello World!");
   }
 
   document.getElementById("msg").onclick = hello;
 
   hello();
  </script>
 </body>
</html>

Functions with argumentsEdit

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.

ObjectsEdit

An object is a structure of variables and some functions used to work with those variables. These include private variables, which should only be referenced or changed using the methods it provides. For example 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.

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 ObjectEdit

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

2014
number

Because information such as the year is 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());
2014
2008

Defining New ObjectsEdit

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!".

this keywordEdit

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. You can use the new keyword with any function to create an object, but it will be much easier to keep track of what you're doing if you only use new with functions that are meant just for the purpose, and mark those functions by naming them with an initial capital letter.

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();

Please notice that the above method is inefficient and will use way too much memory inside the browser, if you need to create a serious javascript class then you must first learn about prototypes.

ExceptionsEdit

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 readingEdit


Previous: Control Structures Index Next: Event Handling
Last modified on 14 July 2013, at 03:24