December 18, 1999 - Extending Instance Objects
December 18, 1999 Extending Instance Objects Tips: December 1999
Yehuda Shiran, Ph.D.
|
Let's take an example. Suppose we want to extend some instances of the String class with a method that picks every second character of the original string and returns them in a new string. Here is the function definition:
function string_pickEven() {
var s = "";
for (var i = 0; i this.length; i+=2) s += this[i];
return s;
}
This is how you extend the string foo with the pickEven method:
foo = new String("abcdefghijk");
foo.pickEven = string_pickEven;
Here is an example for using the extended foo string:
evenString = foo.pickEven();
The string evenString should be equal to "acegik"
.
Notice the difference between instance extension and class extension. Class extension is done via the prototype property, as explained in the previous page. An instance object is extended without the prototype property, as explained above.
You can learn more about passing objects by reading Column 34, Inheritance through Prototypes.