Javascript Basics Part 4

By Mark Kahn

This is the fourth in a 10-part series that will introduce you to the JavaScript language.

In the last article, we covered the basics on how to work with form fields and we delved into functions a bit more. If you don't fully understand any of these concepts, you should read, or re-read the last article.

In this article we will fully explain functions and introduce the concepts of objects in JavaScript.

As you already know, functions in JavaScript are used to perform the same task multiple times. Up until now, we have always called our functions manually with parenthesis: myFunction(). What if you want to run a function when the user performs a specific task? Well you can--using JavaScript--attach a function to almost any event that your user might perform. Let's see this in action by writing a function that counts how many times your user has clicked on the page.

<script type="text/javascript">
var clickCount = 0;
function documentClick(){
	document.getElementById('clicked').value = ++clickCount;
}
document.onclick = documentClick;
</script>

You have clicked on this page <input id="clicked" size="3" onfocus="this.blur();" value="0"> times.
You have clicked on this page times.

In previous articles we have only used the ++ operator after a variable, as in "clickCount++". In this example, however, we are using ++ before the variable. The first example, "clickCount++", adds one to clickCount after its value is read. "++clickCount", on the other hand, adds one to clickCount before its value is read. Since our clickCount variable in this example is initially set to 0, we want to add one to it before we set the value of the input box, thus we write "++clickCount".

If you look at the previous example, it should seem fairly familiar. We define a variable and a function just as we have before. What changes is that instead of calling our function, documentClick(), we are telling our code that we want the function to run every time the user clicks on the document. "document.onclick" binds the function to the document's onclick event.

There are many events like "onclick". We will introduce a few of these, but a few of the most common ones are: onclick, onload, onblur, onfocus, onchange, onmouseover, onmouseout and onmousemove. You can bind a function to these events on any object, such as an image or input box, not just the document. onmouseover and onmouseout are, for example, commonly used on images to create a rollover effect.

You might have also noticed that we referenced our input box differently. We previously discussed that to reference an input box, you should use "document.forms.formName.elements.inputBoxName". While this is a good way to do this, it is not always necessary. In this example, our input box is simply acting as a counter. It is not inside of a form and we do not need it to be. So we give it an ID: id="clicked". IDs can be used to reference any object on your page. IDs must be unique on the page so if you have 5 input boxes with IDs you must give them each different IDs; even if they are only "input1"-->"input5".

Since we are using this input box as a counter, we don't want people to be able to click on it and change its value. This is where another binding, "onfocus", comes into play. "onfocus" is fired whenever the cursor is moved to the object. So if you click on the input box or if you use the tab key to get to it, "onfocus" is called.

We have a very short piece of code in our onfocus event, but it is also very important. It introduces the "this" keyword which is crucial to understand in JavaScript. "this" is a keyword that refers to whatever object the code is running on. In this example "this" is refering to our input box. In this example "this.blur()" is "blurring" our input box, in other words, forcing it to lose focus. Since this is executed as soon as the user focuses on the input box, it makes it "impossible" to change the data.

If "this" is used in a function, it refers to the function itself. If "this" is used in JavaScript code outside of a function, it refers to the window object. The most common uses of "this" are changing a property of the current object, as in the example above, or passing the current object to a function.

Let's look at another example:

<script type="text/javascript">
function showValue(obj){
	alert('You Clicked On ' + obj.value);
}
</script>

<input type="radio" name="fruit" onclick="showValue(this);" value="Apple"  > Apple
<input type="radio" name="fruit" onclick="showValue(this);" value="Orange" > Orange
<input type="radio" name="fruit" onclick="showValue(this);" value="Pear"   > Pear
<input type="radio" name="fruit" onclick="showValue(this);" value="Bananna"> Bananna

You should notice that the onclick event for each of these radio buttons is identical. If you click each of them, however, you get different messages. This is because of the "this" keyword. Since "this" is refering to each of the individual radio buttons, we are passing each radio button to the "showValue" function seperately.

Getting back to functions, we need to describe how to pass arguments to a function. In the previous example, "obj" is an argument. "obj" is going to contain a reference to whatever input box you click on. You can pass as many arguments to a function as you need. If you need 10 arguments, your function could look like:

function myFunction(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10){
	// code goes here
}
In many instances, you might have a function that needs up to a certain number of arguments, but doesn't always need them all. One of the nice things about JavaScript is that you do not need to pass 10 arguments to a function that is declared to accept 10 arguments. If you only pass the first 3, the function will only have the first 3 defined. You need to take this into account when writing your functions. We might have a function that always requires the first 3 arguments, but the next 7 are optional:
function myFunction(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10){
	// do stuff with arg1
	// do stuff with arg2
	// do stuff with arg3
	if(arg4){
		// do stuff with arg4
	}

	if(arg5 && arg6 && arg7){
		// do stuff with arg5, arg6 and arg7
		if(arg8){
			// do stuff with arg8
		}
	}

	if(arg9 || arg10){
		// do stuff with arg9 or arg10
	}
}
You'll notice that all we are doing is saying "if(arg)". If an argument is not passed to a function you get a value of "undefined" when you try to do something with it. "undefined" is a special state in JavaScript saying that the object doesn't exist. When you try to use "undefined" as a boolean (true/false) value, as we are in our if statements, it comes back as false.

So if arg4 is not passed in our above example, it comes back as "undefined" and our if statement is not executed.

What if you don't know how many arguments you need? You could have a function that takes 1-->n arguments and performs an identical task on all of them. Well fortunately JavaScript gives us an "arguments" object in every function. The arguments object contains every argument in the function:

function myFunction(){
	for(var i=0; i<arguments.length; i++){
		alert(arguments[i].value);
	}
}
This code will alert the value of any object(s) you pass to it. If you pass 100 objects, you will get 100 alerts. A more useful function would possibly hide/show any objects you passed to it.

One of the more interesting aspects about JavaScript is the idea that functions are objects and can be passed around like an input box, image or anything else you may have. Take a look at this code, for example:

<script type="text/javascript">
function multiply(){
	var out=1;
	for(var i=0; i<arguments.length; i++){
		out *= arguments[i];
	}

	return out;
}

function add(){
	var out=0;
	for(var i=0; i<arguments.length; i++){
		out += arguments[i];
	}

	return out;
}

function doAction(action){
	alert(action(1, 2, 3, 4, 5));
}
</script>

<button onclick="doAction(multiply)">Test Multiply</button>
<button onclick="doAction(add)"     >Test Add</button>

There is a lot going on in this little bit of code. We start off by simply defining two functions: multiply and add. Our multiply function just multiplies together any numbers you pass to it. Likewise, our add function adds together any numbers you pass to it. The magic starts with the onclick actions of our two buttons. You will notice that when you click either button you are passing an object to the doAction function. Previously, we have always passed variables or HTML objects (like our input boxes in a previous example). In this example we are passing functions. Functions can be passed the same as any other object, and when you pass them they are called the same way as any other function. The only thing that changes is their name.

So our doAction function takes in another function as an argument! If you pass it the multiply function it passes 1 through 5 to our multiply function and we get a value of 120. If you pass the add function to doAction the values 1 through 5 are passed to add and we get a value of 15 as a result.

This is actually one of the most powerful features of JavaScript and we will explore this in more detail in future articles. For now it is important that you understand the concept.

Another important feature regarding functions is the fact that you can nest them inside one another. JavaScript does not support true Object Oriented (OO) design, but this feature allows very similiar features.

In addition to being able to nest functions, it is important to note that there are several different ways to declare a function:

function myFunction(){
	function nestedFunction1(arg1, arg2, arg3){
		alert(arg1+arg2+arg3);
	}

	var nestedFunction2 = function(arg1, arg2, arg3){
		alert(arg1+arg2+arg3);
	}

	var nestedFunction3 = new Function('arg1, arg2, arg3', 'alert(arg1+arg2+arg3);');
}
In this example, nestedFunction1, nestedFunction2 and nestedFunction3 are all identical in function. The only difference is in how they are defined. nestedFunction1 is declared like every function we have seen before this. The syntax for nestedFunction2, on the other hand, is a bit different. We are setting a variable, this.nestedFunction2, to a function. The syntax for this is "variableName = function(arguments){". Likewise for nestedFunction3, we are setting a variable to a new function. This one is drastically different, however, as we are defining our function with strings. This third example is rarely used, but is very useful when it is. It allows you to build a string containing code for a function to execute and then define the function with that string.

That's all for this primer. Our next primer will look at an area we have skipped over until now--Arrays.

Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •