JavaScript Instance Methods

A constructor that is created in JavaScript can have methods defined for it. These are called ‘instance methods.’

For example, suppose the following constructor was defined in JavaScript:

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

In this example, ‘sideLength’ is an instance property and each instantiation of the Square class will have it’s own copy of the ‘sideLength’ property. Instance methods work a little differently. They are defined through the prototype property of the constructor. For example:

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

The perimeter method is thus an instance method of the Square class. Instance methods differ from instance properties in JavaScript in that each instantiation of the instance method is shared among instantiations of the class.

Related articles:
Object-Oriented JavaScript
JavaScript Instance Properties

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.