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

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

Summary
The power of any programming language depends on the extent to which you can modify it for your own needs. The more you are limited to using just the built-in commands and processes, the more you are limited in what you can do with that language. And the harder it is to write sophisticated programs. Thankfully, JavaScript supports user-defined functions, properties, and methods, and uses a simplified object model to create them.

By Gordon McComb

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

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
After an object has been created you can assign a value to it. But instead of just assigning a value to the object itself, you should define a new property for the object, and assign a value to the property. To create a new property and assign a value to it, simply write a variable expression like this:

myobject.property = value;
Suppose you create an object called "customer" and you want to define three properties to it: name, address, and phone. Here's one way to do it:
customer = new makeSimpleObject();
customer.name = "Fred";
customer.address = "123 Main Street";
customer.phone = "555-1212";

function makeSimpleObject() {
        return (this);
}
You can verify that you've indeed created a new object and assigned properties to the object my adding an alert method to display one of the properties. For example, you could put this after the customer.phone line. When you run the script the alert box will say "Fred."
alert (customer.name);

Defining properties when you create the object
Another method of defining properties for objects is to include the property names in the object function. You can use this technique to simultaneously create a new object and define the property values. All it takes is a few more lines of code in the object function.

customer = new makeCustomer("Fred", "123 Main Street", "555-1212");
alert (customer.name);

function makeCustomer(Name, Address, Phone) {
        this.name = Name;
        this.address = Address;
        this.phone = Phone;
}
Note the series of this statements. Each this statement assigns a property to the current object, which is the one being created in the makeCustomer object function. Three parameters are passed to the object statement: the customer's name, address, and phone number. These parameters are used to define the contents of the three properties, which are name, address, and phone.

JavaScript imposes no limitations on the number of properties you can assign to an object. To include as customer object, just do this:

customer = new makeCustomer("Fred", "123 Main Street", "555-1212");
customer.salutation = "Mr.";
Note that other objects you create with the makeCustomer object function will have just the three base properties, but this object for Fred will have an additional property for the salutation. Properties added later do not affect other objects created with the same object function.

Creating user-defined methods
A user-defined method is yet another way of using functions in JavaScript. Methods act upon objects -- either objects built into JavaScript, or objects that you've created. A method changes or manipulates an object in some way. For instance, suppose you want to insert the various contents of the customer object: name, address, and phone number. Write the code to insert the object contents, then stuff the code in a function. Call the function, using the customer object as a parameter, like so:

customer = new makeCustomer("Fred", "123 Main Street", "555-1212");
displayCustomer (customer);

function displayCustomer (cust_obj) {
        Temp = "Name: " + cust_obj.name + "<BR>";
        Temp += "Address: " + cust_obj.address + "<BR>";
        Temp += "Phone: " + cust_obj.phone + "<BR>";
        document.write (Temp + "<BR>");
}
Here's a fully functioning user-defined property example if you'd like to try this out. Load the script; JavaScript will display three lines of customer data. (Reload the document if you want to run it again.)
<HTML>
<HEAD>
<TITLE>Object Method Example</TITLE>
<SCRIPT LANGUAGE="JavaScript">

function run () {
customer = new makeCustomer("Fred", "123 Main Street", "555-1212");
displayCustomer (customer);
}

function displayCustomer (cust_obj) {
        Temp = "Name: " + cust_obj.name + "<BR>";
        Temp += "Address: " + cust_obj.address + "<BR>";
        Temp += "Phone: " + cust_obj.phone + "<BR>";
        document.write (Temp + "<P>");
}

function makeCustomer(Name, Address, Phone) {
        this.name = Name;
        this.address = Address;
        this.phone = Phone;
}

run()

</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
The other method is to create a method for the customer object. With this approach, you call the method as part of the object. This helps in defining special method functions that are designed for -- and only for -- certain kinds of objects. This process forms one of the foundations of object-oriented programming, where objects contain their own unique methods of operation. Here's the same script as above, modified so that the customer object contains the displayCustomer method.
<HTML>
<HEAD>
<TITLE>Object Method Example</TITLE>
<SCRIPT LANGUAGE="JavaScript">

function run () {
        customer = new makeCustomer("Fred", "123 Main Street", "555-1212");
        customer.displayCustomer();
}

function displayCustomer () {
        Temp = "Name: " + this.name + "<BR>";
        Temp += "Address: " + this.address + "<BR>";
        Temp += "Phone: " + this.phone + "<BR>";
        document.write (Temp + "<P>");
}

function makeCustomer(Name, Address, Phone) {
        this.name = Name;
        this.address = Address;
        this.phone = Phone;
        this.displayCustomer = displayCustomer;
}

run()

</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
As you can see, to display the customer data, you call the displayCustomer method, like so:
customer.displayCustomer();
Notice a few other changes in this version: When you write your own methods for objects, you'll follow the pattern used in the displayCustomer() function. There's no need to pass parameters to the function unless you need to. Refer to properties using the "this" keyword." And, add the name of the method function in the function that creates the object -- in this case, it's the makeCustomer object function.

Conclusion
Much of JavaScript's power comes from user-defined functions -- functions you make yourself. With your own functions, you create what is in essence your own JavaScript commands. And, you use functions to build JavaScript objects and methods. Master functions, and you'll go far in mastering JavaScript.

About the author
Gordon McComb is an author, consultant, and lecturer. He has written 50 books and more than a thousand magazine articles during his 20 years as a professional writer. More than a million copies of his books are in print. Gordon also writes a weekly syndicated newspaper column on computers, reaching several million readers worldwide. Gordon's latest book is The JavaScript Sourcebook, available from Wiley Computer Publishing. He can be reached at gordon.mccomb@javaworld.com.



WebNation Main | Web Page Prices | Web Advertising Tips | Questions You Should Ask Your Web Page Designer | Contact WebNation