Objects inherit from a prototype object (of type Object), created by the constructor. There is only one prototype object for each class, so put constants and methods there, just once rather than on every object of the class. Eg,
/* Constructor */
function Circle (centrePoint, radius)
{
this.centre = centrePoint;
this.radius = radius;
}
Circle.prototype.PI = 3.1415926; // Constant PI
function circleArea ()
{
return this.PI * this.radius * this.radius;
}
Circle.prototype.area = circleArea; // Method area ()
var c = new Circle ({ x:1, y:2}, 3);
alert ("Area = " + c.area ());
We could have declared the area() function as a method all in one step, in which case the function declaration does not need a name, arguably the best way:
Circle.prototype.area = function ()
{
return this.PI * this.radius * this.radius;
}
Built-in (predefined) objects also have prototype objects to which you can add properties.
You need to be aware of these.
obj.p
will automatically read from the prototype if the prototype has property p
but obj
does not.obj.p
will cause p
to become a property of obj
if previously it was only in the prototype. From then on, obj.p
hides obj.prototype.p
- hence the prototype is mostly useful for functions (methods) and constants only.obj.constructor
so for any function f
(which is always an object), f.prototype.constructor == f