Each object in JavaScript has a prototype, which is another object
that it inherits properties from. The prototype fulfills a role similar
to that of the superclass in a class-based object-oriented language. If
a referenced property is not found in an object, it is searched for in
the object's prototype. This is recursive, meaning that if the property
is not in the object's prototype, it is searched for in the prototype's
prototype, and so on. If a property is assigned to a constructor
function's prototype, it will be available to every object created with
that constructor. In contrast, assigning a property to the constructor
function itself only makes the property available from that function
object. The latter is comparable to defining static methods and members in Java (although static methods are in a subclass's scope).
The important point for users of the
SE script library is that functions (methods) that are noted as being in
the prototype (for example, AbstractContainer.prototype.addToEditor)
are available from any object created directly or indirectly from that constructor,
while functions that are not in the prototype (described as
"static") must be called through the object they are defined on
(for example, FontUtils.availableFontFamilies). An example:
Number.prototype.monetize = function monetize() {
return sprintf( "$%.2f", this/100 );
}
var n = 175;
println( n.monetize() );
Number.nextNatural = function nextNatural() {
return ++Number.nat;
}
Number.nat = 0;
println( Number.nextNatural() );
println( Number.nextNatural() );
println( n.nextNatural() );