Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Customizing Built-In Objects

JavaScript includes a feature that enables you to extend the definitions of built-in objects. For example, if you think the String object doesn't quite fit your needs, you can extend it, adding a new property or method. This might be very useful if you were creating a large script that used many strings.

You can add both properties and methods to an existing object by using the prototype keyword. (A prototype is another name for an object's definition, or constructor function.) The prototype keyword allows you to change the definition of an object outside its constructor function.

As an example, let's add a method to the String object definition. You will create a method called heading, which converts a string into an HTML heading. The following statement defines a string called title:

title = "Fred's Home Page";

This statement would output the contents of the title string as an HTML Level 1 header:

document.write(title.heading(1));

Listing 15.1 adds a heading method to the String object definition that will display the string as a heading, and then displays a simple example.

Example 15.1. Adding a method to the String object

<html>
<head><title>Test of heading method</title>
</head>
<body>
<script LANGUAGE="JavaScript1.1" type="text/javascript1.1">
function addhead (level) {
   html = "H" + level;
   text = this.toString();
   start = "<" + html +">";
   stop = "</" + html +">";
   return start + text + stop;
}
String.prototype.heading = addhead;
document.write ("This is a test".heading(1));
</script>
</body>
</html>

First, you define the addhead() function, which will serve as the new string method. It accepts a number to specify the heading level. The start and stop variables are used to store the HTML "begin header" and "end header" tags, such as <h1> and </h1>.

After the function is defined, use the prototype keyword to add it as a method of the String object. You can then use this method on any String object, or in fact any JavaScript string. This is demonstrated by the last statement, which displays a quoted text string as a Level 1 header.

Share ThisShare This

Informit Network