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