2.1. Defining Classes

Since JavaScript is a prototype-based language rather than an object-oriented language, defining classes is a bit long winded.

Consider a simple Point class that has two attributes, x and y.

This may be defined in raw JavaScript as:

var Point = function(x,y)
{
       this.x = x;
       this.y = y;
}

function Point_toString()
{
       return "Point(" +this.x+","+this.y+")";
}

Point.prototype.toString = Point_toString;

New instances may be created using the new keyword:

var myPoint = new Point(0,0);

Get Prototype and Scriptaculous: Taking the Pain out of JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.