Sams Teach Yourself JavaScript in 24 Hours Free Open Book

Sams Teach Yourself JavaScript in 24 Hours

Previous Page
Next Page

Extending 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 enables 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 heading:

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

Listing 6.4 adds a heading method to the String object definition that will display the string as a heading, and then displays three headings using the method.

Listing 6.4. Adding a Method to the String Object

<html>
<head><title>Test of heading method</title>
</head>
<body>
<script LANGUAGE="JavaScript" type="text/javascript">
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 heading 1".heading(1));
document.write ("This is a heading 2".heading(2));
document.write ("This is a heading 3".heading(3));
</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 three statements, which display quoted text strings as level 1, 2, and 3 headers.

Try It Yourself

Storing Data in Objects

Now you've created a new object to store business cards and a method to print them out. As a final demonstration of objects, properties, functions, and methods, you will now use this object in a web page to display data for several cards.

Your script will need to include the function definition for PrintCard(), along with the function definition for the Card object. You will then create three cards and print them out in the body of the document. We will use separate HTML and JavaScript files for this example. Listing 6.5 shows the complete script.

Listing 6.5. An Example Script That Uses the Card Object

// define the functions
function PrintCard() {
line1 = "<b>Name: </b>" + this.name + "<br>\n";
line2 = "<b>Address: </b>" + this.address + "<br>\n";
line3 = "<b>Work Phone: </b>" + this.workphone + "<br>\n";
line4 = "<b>Home Phone: </b>" + this.homephone + "<hr>\n";
document.write(line1, line2, line3, line4);
}
function Card(name,address,work,home) {
   this.name = name;
   this.address = address;
   this.workphone = work;
   this.homephone = home;
   this.PrintCard = PrintCard;
}
// Create the objects
sue = new Card("Sue Suthers", "123 Elm Street", ldquo;555-1234",
 "555-9876");
phred = new Card("Phred Madsen", "233 Oak Lane", "555-2222",
 "555-4444");
henry = new Card("Henry Tillman", "233 Walnut Circle", "555-1299"
, "555-1344");
// And print them
sue.PrintCard();
phred.PrintCard();
henry.PrintCard();

Notice that the PrintCard() function has been modified slightly to make things look good with the captions in boldface. To use this script, save it as cardtest.js. Next, you'll need to include the script in a simple HTML document. Listing 6.6 shows the HTML document for this example.

Listing 6.6. The HTML File for the Card Object Example

<html>
<head>
<title>JavaScript Business Cards</title>
</head>
<body>
<h1>JavaScript Business Card Test</h1>
<p>Script begins here.</p><hr>
<script language="JavaScript" type="text/javascript"
   src="cardtest.js">
</script>
<p>End of script.</p>
</body>
</html>

To test the script, save the HTML document in the same directory as the cardtest.js file you created earlier, and then load the HTML document into a browser. The browser's display of this example is shown in Figure 6.2.

Figure 6.2. Internet Explorer displays the output of the business card example.


By the Way

This example isn't a very sophisticated database because you have to include the data for each person in the script. However, an object like this could be used to store a database record retrieved from a database server with thousands of records.



Previous Page
Next Page
Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y]


     Main Menu
Sams Teach Yourself JavaScript in 24 Hours
Table of Contents
Copyright
About the Author
Acknowledgments
Part I: Introducing the Concept of Web scripting and the JavaScript Language
Part II: Learning JavaScript Basics
Hour 5. Using Variables, Strings, and Arrays
Hour 6. Using Functions and Objects
Using Functions
Introducing Objects
Using Objects to Simplify Scripting
Extending Built-in Objects
Summary
Q&A
Quiz Questions
Quiz Answers
Exercises
Hour 7. Controlling Flow with Conditions and Loops
Hour 8. Using Built-in Functions and Libraries
Part III: Learning More About the DOM
Part IV: Working with Advanced JavaScript Features
Part V: Building Multimedia Applications with JavaScript
Part VI: Creating Complex Scripts
Part VII: Appendixes
Index


More Books
PHP Hacks
Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
The Koran (Holy Qur'an)
Macromedia Flash 8 Bible
Search Engine Optimization for Dummies
YouTube Traffic
PHP 5 for Dummies
Harry Potter and The Chamber of Secrets
Harry Potter and the Sorcerer's Stone
The Pilgrim's Progress
Wireless Hacks
Flash Hacks. 100 Industrial-Strength Tips & Tools
PayPal Hacks. 100 Industrial-Strength Tips and Tools
Amazon Hacks
Pdf Hacks
The Da Vinci Code
Google Hacks
The Holy Bible
Windows XP For Dummies
Harry Potter and the Half-Blood Prince
Seo Book
Upgrading and Repairing Networks
Macromedia Dreamweaver 8 UNLEASHED
Windows XP Annoyances
Windows XP Hacks
Microsoft Windows XP Power Toolkit
Teach Yourself MS Office In 24Hours
iPod & iTunes Missing Manual
PC Hacks 100 Industrial-Strength Tips and Tools
PC Overclocking, Optimization, and Tuning - 2th Edition
PC Hardware In A Nutshell 3rd Edition
PC Hardware in a Nutshell, 2nd Edition
Upgrading and Repairing PCs
Google for Dummies
MySQL Cookbook
Teach Yourself Macromedia Flash 8 In 24 Hours
PHP CookBook
Sams Teach Yourself JavaScript in 24 Hours
PHP5 Manual
Free Games Paper Airplanes
500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele