Entry
How can I add a method to an existing object "class" like Strings/Dates etc?
Feb 12th, 2000 16:49
Martin Honnen,
JavaScript knows so called prototype based class definition and
inheritance. Every object has a constructor (e.g.
String
is the constructor for String objects) which is associated with a
prototype object (e.g.
String.prototype
) defining common properties and methods.
For instance the common methods of String objects are defined as
properties of the prototype property of the String constructor e.g. try
alert(String.prototype.toLowerCase)
and you will find it is a function.
The flexible thing about JavaScript is that you can add properties to
such a prototype so for instance after defining the function
function stringReverse (str) {
var s = this ? this : str;
var r = '';
for (var i = s.length - 1; i >= 0; i--)
r += s.charAt(i);
return r;
}
you can add it as a property to the prototype object of the String
constructor with
String.prototype.reverse = stringReverse;
and then all your String objects have a reverse method you can call e.g.
var s = 'Kibology';
var sr = s.reverse();
alert(sr);
Note that such a function which serves as a object method refers to the
called object in its body as the
this
object, i.e. a method of an object must have a means of referring to
the object which is called e.g. in
s.reverse()
s is the string object whose method is called and then s is passed in
as the this object.