SiteExperts.com Logo Home | Community | Developer's Paradise | Jobs
User Groups | Site Tools | Site Information | Search

Inside Technique : Extending JavaScript with Function Pointers : Creating Custom Objects

Function pointers provide the foundation for creating your own custom objects. When you create a custom object you add methods to the object by assigning references to functions to members of your object. Below we create a simple square object:

function Square_Area() {
	return this.width * this.width
}

function Square_Perimeter() {
	return this.width * 4
}

function Square(width) {
	this.width = width
	this.area = Square_Area
	this.perimeter = Square_Perimeter
}

var bigSquare = new Square(25)
document.write(bigSquare.area()) // Display the area

First, notice how a function can act as a constructur for an object. Calling new functionName creates and returns a new instance of the object. With this object instance, you can access the different methods and properties. Each method is created by adding a property to the object that is assigned to a function elsewhere in your script.

It is important to recognize that each time you use the new operator you create a new instance of an object. Therefore when calling the area or perimeter method on a sqaure it is being called within the context of a particular instance. For example, if you create two square objects you are creating two instances of the object. Imagine we create two squares, one with a width of 12 and the other with a width of 25. If you call the area or perimeter method on either of these square objects, you want to make sure the object is called with the correct context (eg., calling the area method on the square with a width of 12 should return 144).

Custom objects demonstrate one scenario of the usefulness of the function pointer. Through the remainder of this article, we explain how function pointers can also be used to fix compatibility issues between browsers. You can either extend the browser with new functionality or override the built-in implementation simply by rewriting the functionality. Next we explain how to take advantage of the fact that all built-in JavaScript functions are actually methods of a particular object