'Personalized JavaScript': User-defined functions, objects, and methods

How to take full advantage of JavaScript by moving beyond its built-in commands

As a modern programming language, JavaScript endorses full extensibility by letting you define your own functions. This allows you to create routines you can use over and over again. You save time in re-using common "components," and by designing your own functions you can extend JavaScript's base language to suit your needs. Think of it as "personalized JavaScript."

Since JavaScript is based on objects, a JavaScript function can easily be turned into an object, and a method for that object. So, not only can you create user-defined objects to do your bidding, you can create your own objects that behave in exactly the way you want. And you can create methods that act upon those objects. While this sounds powerful -- and it is -- the process of creating functions, objects, and methods is very easy in JavaScript.

Introducing functions

Use the function statement to create your own JavaScript function. The bare-bones syntax is:

function name (params) {
    ... function stuff...
}
  • name is the unique name of the function. All function names in a script must be unique.
  • params is one or more parameter variables you pass to the function.
  • function stuff is the instructions carried out by the function. You can put most anything here.

Notice the { and } brace characters; these define the function block, and are absolutely necessary. The braces tell JavaScript where a function begins and ends. The parentheses around the parameters also are required. Include the parentheses even if the function doesn't use parameters (and many don't).

Names for your user-defined functions are up to you, just as long as you use only alphanumeric characters (the underscore character _ also is permitted). Function names must start with a letter character, but can include numbers elsewhere in the name.

I've stuck with the JavaScript style of function name capitalization -- that is, initial lower case, then upper-case characters if the function name is composed of composite words. For example, myFuncName, yourFuncName, or theirFuncName. Function names are case-sensitive; be sure to use the same capitalization when you refer to the function elsewhere in the script. JavaScript considers myFunc different from Myfunc.

To differentiate between functions and variables, I prefer to give my variables initial upper case characters, such as MyStuff. This immediately differentiates it from a function, which would use a the capitalization myStuff. Of course, you are free to adopt any capitalization scheme you wish.

Defining and using a function

The best way to describe the how and why of a function is to show a simple one in action. Here's a basic function that displays "Hello, JavaScripters!" and is an obvious takeoff on the "Hello World!" example you see for new programming languages.

function basicFunction () {
    alert ("Hello JavaScripters!");
}

This merely defines the function. JavaScript will do nothing with it unless the function is referenced someplace else in the script. You have to call the function in order to use it. Calling a user-defined function is the same as calling a built-in JavaScript function -- you merely provide the name of the function in your script. This serves as the function call. When JavaScript encounters the function call, it dashes off to complete whatever instructions are in that function. When the function is over, JavaScript returns to the point immediately after the function call, and processes the remainder of the script.

To call the function above, just include the text basicFunction() -- note the empty parentheses, as they are required. Here's a working example of the Hello JavaScripters program.

<HTML> <HEAD> <TITLE>Basic Function Example</TITLE> <SCRIPT LANGUAGE="JavaScript"> function basicFunction () { alert ("Hello JavaScripters!"); }

basicFunction();

</SCRIPT> </HEAD> <BODY> Page has loaded. </BODY> </HTML>

The browser processes the contents of the <SCRIPT> tag as the document loads. When it encounters the basicFunction() function call, it pauses momentarily to process the function, and an alert box appears. Click OK and the remainder of the page finishes loading.

Calling a function with an event handler

A common way of calling a function is to include a reference to it in a form button or hypertext link. Processing a user-defined function when the user clicks a form button is perhaps the easiest of all. You use the onClick event handler to tell JavaScript that when the user clicks on the button, the function specified should be processed. Here's a revised version of the previous example, showing how basicFunction is called when the form button is clicked.

<HTML> <HEAD> <TITLE>Basic Function Example</TITLE> <SCRIPT LANGUAGE="JavaScript"> function basicFunction () { alert ("Hello JavaScripters!"); }

</SCRIPT> </HEAD> <BODY> Click to call function. <FORM> <INPUT TYPE="button" VALUE="Click" onClick="basicFunction()"> </FORM> </BODY> </HTML>

Notice the onClick syntax in the <INPUT> tag. The event you want to process on a click is a call to basicFunction. This event is surrounded by double quotes.

Passing a value to a function

JavaScript functions support passing values -- or parameters -- to them. These values can be used for processing within the function. For instance, rather than having the alert box say "Hello JavaScripters!" whenever you call it, you can have it say anything you like. The text to display can be passed as a parameter to the function.

To pass a parameter to a function, provide a variable name as the parameter in the function definition. You then use that variable name elsewhere in the function. For example:

function basicExample (Text) {
    alert (Text);
}

The variable name is Text, and is defined as the parameter for the function. That variable is then used as the text to display in the alert box. When calling the function, provide the text you want to show as a parameter of the function call:

basicExample ("This says anything I want");

Passing multiple values to a function

You can pass multiple parameters to a function. As with built-in JavaScript functions and methods, separate the parameters with commas:

multipleParams ("one", "two");
...
function multipleParams (Param1, Param2) {
...

When you define a function with multiple parameters, be sure the parameters are listed in the same order in the function call. Otherwise, your JavaScript code may apply the parameters to the wrong variables, and your function won't work right.

Here's a working example of a function with multiple parameters. It takes two parameters: an input string and a number value. The number value indicates how many characters on the left of the string you want to display in the alert box. When you run the following script, the alert box displays "This is" -- the first seven characters of the input string.

<HTML> <HEAD> <TITLE>Global Variable Example</TITLE> <SCRIPT LANGUAGE="JavaScript"> lefty ("This is a test", 7);

function lefty (InString, Num) { var OutString=InString.substring (InString, Num); alert (OutString); } </SCRIPT> </HEAD> <BODY> </BODY> </HTML>

Returning a value from a function

The functions described so far don't return a value; that is, they do whatever magic you want them to do, then end. No "output" value is provided by the function. In some other languages, such return-less functions are called subroutines. However, in JavaScript (like in C and C++), "functions are functions" whether or not they return a value.

It's easy to return a value from a function: use the return statement, along with the value you wish to return. This is handy when you want your function to churn through some data and return the processed result. Take the "lefty" function from above. Instead of displaying the chopped-off string, you can return it to the calling function, and use the return value any way you want.

<HTML> <HEAD> <TITLE>Global Variable Example</TITLE> <SCRIPT LANGUAGE="JavaScript"> var Ret = lefty ("This is a test", 7); alert (Ret);

function lefty (InString, Num) { var OutString=InString.substring (InString, Num); return (OutString); }

</SCRIPT> </HEAD> <BODY> </BODY> </HTML>

This script does essentially the same one as the previous example, but instead of always displaying the chopped-off text, the function merely returns the processed value. The return value is captured in a variable, and you are free to use that variable in any way you wish. The above shows the Ret variable used with an alert box, but you can use it in other ways, too. For example, you can write the contents of the Ret variable using the document.write method:

document.write (Ret);

Defining local variables within functions

By default all JavaScript variables are declared global for the document that created them. That means when you define a variable in a function, it is also "visible" to any other portion of the script on that document. For example, in the following global variable test, the variable test is visible to the showVar function, even though the variable is defined in the loadVar function.

<HTML> <HEAD> <TITLE>Global Variable Example</TITLE> <SCRIPT LANGUAGE="JavaScript">

function showVar () { alert (test) }

function loadVar () { test = "6" }

loadVar();

</SCRIPT> </HEAD> <BODY> Click to call function. <FORM> <INPUT TYPE="button" Value="Click" onClick="showVar()"> </FORM> </BODY> </HTML>

Global variables aren't always what you want. Instead, you want variables that are local to the function. These variables exist only as long as JavaScript is processing the function. When it exits the function, the variables are lost. In addition, a local variable of a given name is treated as a separate entity from a global variable of the same name. In this way, you don't have to worry about reuse of variable names. The local variable in the function won't have any effect on the global variable used elsewhere in the script.

To declare a local variable, add the var keyword to the beginning of the variable name in the function. This tells JavaScript you want to make the variable local to that function. As a test, change the loadVar function above to the following, and re-load the script. When you click the button, JavaScript tells you the variable doesn't exist. This is because test is only local to the loadVar function, and does not exist outside the function.

function loadVar () {
    var test = "6"
}

Calling one function from another function

Code inside a function behaves just like code anywhere else. This means you can call one function from inside another function. This allows you to "nest" functions so that you can create separate functions, which each perform a specific task, and then run them together as a complete process, one right after the other. For example, here's a function that calls three other mythical functions, each one returning a string of text that has been altered in some way.

function run () {
    var Ret = changeText ("Change me");
    alert (Ret);
    document.write (Ret);
}
function changeText (Text) {
    Text = makeBold (Text);
    Text = makeItalics (Text);
    Text = makeBig (Text);
    return (Text);
}
function makeBold (InString) { 
    return (InString.bold());
}
function makeItalics (InString) {
    return (InString.italics());
}
function makeBig (InString) {
    return (InString.big());
}

Creating objects with user-defined functions

JavaScript is based on objects: the window is an object, links are objects, forms are objects, even Netscape itself (or other browser) is an object. Using objects can help make programming easier and more streamlined. You can extend the use of objects in JavaScript by making your own. The process uses functions in a slightly modified way. In fact, you'll be surprised how easy it is to make your own JavaScript objects.

Making a new object entails two steps:

  • Define the object in a user-defined function.
  • Use the new keyword to create (or instantiate) the object with a call to the object function.

Here's an example of the world's simplest user-defined JavaScript object:

// this part creates a new object ret = new makeSimpleObject();

// this part defines the object function makeSimpleObject() {}

I've called the new object ret; use any valid variable name for the new object (I use lower-case letters for variables that contain objects, so it's easier to tell that the variable contains an object).

You can use the same object function to create any number of new objects. For instance, these lines create four new and separate objects: eenie, meenie, minie, and moe:

eenie = new makeSimpleObject();
meenie = new makeSimpleObject();
minie = new makeSimpleObject();
moe = new makeSimpleObject();

Actually, there is even a shortcut to the above "world's simplest JavaScript object." You don't need to define an object function to make a bare-bones object. JavaScript supports a generic Object() object, which you can use to make new objects. The following does the same as the above, without an explicit object function:

eenie = new Object();

Defining new properties to already-made objects

Related:
1 2 Page 1
Page 1 of 2