Custom Objects in JavaScript


A custom object

function CreditCard (name, number, expiry)
{
	this.name = name;
	this.number = number;
	this.expiry = expiry;
}

An object method

function printCard ()
{
	line1 = "Name : " + this.name + "<\BR>\n";
	line2 = "Number : " + this.number + "<\BR>\n";
	line3 = "Expiry : " + this.expiry + "<\BR>\n";
	document.write (line1, line2, line3);
}

Adding the method to the custom object

function CreditCard (name, number, expiry)
{
	this.name = name;
	this.number = number;
	this.expiry = expiry;
	this.printCard = printCard;
}

Creating an object instance

john = new Card ();
john.name = "John Smith";
john.number = "1234 567890 1234";
john.expiry = "09/99";
jim = new Card("Jim Smythe", "1234 567890 5678", "01/99");

Customising built-in objects

The document.write statement below would output the contents of the title string as an HTML level 1 header.

title = "My Home Page";
document.write (title.heading(1));