Archive for September 20, 2007

JavaScript Prototypes

Posted in JavaScript, Technology, internet, programming on September 20, 2007 by Joey

In JavaScript, when a function is defined a property called prototype is automatically created. Properties and methods can be added to this prototype. Any properties or methods added to this prototype will be available to any instantiated instances of the function. The function is a constructor and therefore is similar to a object-oriented class.

For instance, if a constructor function exists for a square, as follows:

function Square(intSideLength)
{

this.perimeter = 4*intSideLength;

this.area = 2*intSideLength;
}

Then a property can be added to all instances of the Square class, as follows:

Square.prototype.sides = 4;

Since this property has been set up, it can be accessed on all instantiated instances of the Square class. For example:

var mySquare = new Square(5);
document.write(mySquare.sides);

Methods can also be added to prototypes:

function Square(intSideLength)
{
this.sideLength = intSideLength;
}

Square.prototype.perimeter = function() {return 4*this.sideLength;}

var mySquare = new Square(5);
document.write(mySquare.perimeter());

Related articles:
Object-oriented JavaScript