Object-Oriented Programming with JavaScript, Part I: Inheritance: Emulating instanceOf() - Doc JavaScript | WebReference

Object-Oriented Programming with JavaScript, Part I: Inheritance: Emulating instanceOf() - Doc JavaScript


Object-Oriented Programming with JavaScript, Part I: Inheritance

Emulating instanceOf()

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.prototype)
     {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:

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));
}

You can probe the superclass of any object via its constructor property. This property returns the function by which the object was created with the new operator. All objects (both native and user-defined) inherit from the Object object. Since the Object object supports the constructor property, all objects supports it as well. Let's look at the Employee object:

function Employee() {
  this.dept = "HR";
  this.manager = "John Johnson";
}
function printProp() {
  var Ken = new Employee();
  alert(Ken.constructor);
}

When you ask for the constructor property, you should get a listing of the Employee function:

Next: How to classify and print objects

http://www.internet.com


Produced by Yehuda Shiran and Tomer Shiran
All Rights Reserved. Legal Notices.
Created: March 12, 2001
Revised: March 12, 2001

URL: http://www.webreference.com/js/column79/7.html