spacer
Yehuda Shiran March 3, 2001
Finding the Object's Superclass
Tips: March 2001

Yehuda Shiran, Ph.D.
Doc JavaScript

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

Sometimes, you need to find out if a certain object is an instance of a given class (constructor function). In other languages, this operation is called instanceOf(). JavaScript does not support the instanceOf() method, but we can write one ourselves, using the internal __proto__ (two underscores on each side) property. The algorithm is based on searching the object's constructor along the inheritance chain, using __proto__:

function instanceOf(object, constructorFunction) {
  while (object != null) {
    if (object == constructorFunction.prototyp) {return true}
	 object = object.__proto__;
  }
  return false;
}

The following code segment defines three classes: State, City, and Street. The Street's prototype is City, and the City's prototype is State. If UniversityAvenue is an instance of Street, it is also an instance of City and State. This demo (Netscape only) proves it by showing all the above instanceOf() relationships to be true:

<SCRIPT LANGUAGE="JavaScript">
<!--
function instanceOf(object, constructorFunction) {
  while (object != null) {
    if (object == constructorFunction.prototype) {return true}
    object = object.__proto__;
  }
  return false;
}
function State() {
}

function City() {
}
City.prototype = new State;

function Street() {
}

Street.prototype = new City;

var UniversityAvenue = new Street();
function demo() {
  alert("instanceOf(UniversityAvenue, Street) is " + instanceOf(UniversityAvenue, Street));
  alert("instanceOf(UniversityAvenue, City) is " + instanceOf(UniversityAvenue, City));
  alert("instanceOf(UniversityAvenue, State) is " + instanceOf(UniversityAvenue, State));
}

// -->
</SCRIPT>


People who read this tip also read these tips:

Look for similar tips by subject:

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