spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / experts / javascript / column34


Extending Instance Objects with Methods

Developer News
News Flash: Adobe Has iPhone Workaround
Adobe's Flash 10.1 Goes Mobile (Minus iPhone)
A Salute to Visionary CEOs

JavaScript lets you extend not only classes of objects, but also instances of a class. When you extend instances of a certain class, all other instances are unaffected and are not extended. This capability allows you to differentiate between instances of the same class, and practically you end up with two types of instances that inherit the properties of the main class.

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.

http://www.internet.com

Produced by Yehuda Shiran and Tomer Shiran

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Building a Banking Application Home Page with OOP · Mixing Scripting Languages · Review: phpFox, a Social Networking CMS with all the Bells and Whistles
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Enterprise 2.0: Social Networking in the Cloud · BroadSoft Marketplace Hastens Pace of Telephony Innovation · Review: HTC Hero for Sprint


Created: January 18, 1999
Revised: January 21, 1999

URL: http://www.webreference.com/js/column34/instance.html