Main Page

Modifying Objects

Modifying Objects
Creating your own objects is just part of the fun in ECMAScript. How would you like to modify the
behavior of existing objects? This is completely possible in ECMAScript, so dream up whatever methods
you’d like for a
String
,
Array
,
Number
, or any other object, because the possibilities are endless.
Remember the
prototype
object from an earlier section in this chapter? You already know that each
constructor has a
prototype
property that can be used to define methods. What you don’t already
know is that each of the native objects in ECMAScript also has a
prototype
property that can be used
in the exactly same way.
Creating a new method
You can define a new method for any existing class by using its
prototype
property, just as you would
with your own classes. For instance, remember the
toString()
method of
Number
that outputs a hexa-
decimal string if you pass in 16 as an argument? Wouldn’t it be nicer to have a
toHexString()
method
to handle the process? It’s simple to create it:
Number.prototype.toHexString = function () {
return this.toString(16);
};
In this context, the
this
keyword points to the instance of
Number
and so has full access to all the
Number
methods. With this code, it is possible to do this:
var iNum = 15;
alert(iNum.toHexString()); //outputs “F”
Because the number 15 is equal to hexadecimal F, the alert displays
“F”
. And remember the discussion
about using an
Array
as a queue? The only thing missing was properly named methods. You can add
enqueue()
and
dequeue()
to
Array
and just have them call the existing
push()
and
shift()
methods
respectively:
Array.prototype.enqueue = function(vItem) {
this.push(vItem);
};
Array.prototype.dequeue = function() {
return this.shift();
};
You can also, of course, add methods that don’t rely on existing methods at all. For example, say that
you want to determine the position of a particular item in an array. You have no native method to do
such a thing. You can easily create a method that does this:
Array.prototype.indexOf = function (vItem) {
for (var i=0; i < this.length; i++) {
if (vItem == this[i]) {
return i;
99
Object Basics
06_579088 ch03.qxd 3/28/05 11:36 AM Page 99


JavaScript EditorFree JavaScript Editor     Ajax Editor


©