Main Page

Redefining an existing method

}
}
return -1;
}
This method, named
indexOf()
to keep it consistent with the
String
method of the same name,
searches each item in the array until it finds the equivalent of the item passed in. If the item is found,
the method returns the position; if not, the method returns
–1
. With this defined, the following code is
possible:
var aColors = new Array(“red”, “green”, “yellow”);
alert(aColors.indexOf(“green”)); //outputs “1”
Lastly, if you want to add a new method to every native object in ECMAScript, you must define it on the
Object
’s prototype property. As discussed in the last chapter, all native objects inherit from
Object
, and
so any changes to
Object
are reflected in all native objects. For example, if you want to add a method
that outputs the current value of the object in an alert, you do the following:
Object.prototype.showValue = function () {
alert(this.valueOf());
};
var str = “hello”;
var iNum = 25;
str.showValue(); //outputs “hello”
iNum.showValue(); //outputs “25”
Here, both the
String
and
Number
objects inherit the
showValue()
method from
Object
, displaying
“hello”
and
“25”
when called on their respective objects.
Redefining an existing method
Just as it is possible to define new methods for existing classes, it is also possible to redefine existing
methods. As discussed in the previous chapter, function names are simply pointers to functions, and as
such, can be easily changed to point to other functions. What happens if you change a native method,
such as
toString()
?
Function.prototype.toString = function () {
return “Function code hidden”;
};
The previous code is perfectly legal and works as expected:
function sayHi() {
alert(“hi”);
}
alert(sayHi.toString()); //outputs “Function code hidden”
100
Chapter 3
06_579088 ch03.qxd 3/28/05 11:36 AM Page 100


JavaScript EditorFree JavaScript Editor     Ajax Editor


©