Visit Mozilla.org

Core JavaScript 1.5 Reference:Global Objects:Object:isPrototypeOf

From MDC


isPrototypeOf allows you to check whether or not an object instance has a class in question as one of its parents.

For example, the following code creates a class Question and another class SecondaryQuestion that extends Question:

function Question () {
  this.answer = 42;
}

function SecondaryQuestion () {

}
SecondaryQuestion.prototype = new Question();

Later on down the road, if you instantiate SecondaryQuestion and need to check if it has Question as a parent class, you could do this:

var myquestion = new SecondaryQuestion();

...

if (Question.prototype.isPrototypeOf(myquestion)) {
  // do something with the question
}

This particularly comes in handy if you have a function or class method that can only accept an instance of a certain class as its parameter:

function guessAnswer(q) {
  if (Question.prototype.isPrototypeOf(q)) {
    // Try to answer the question.
    // This doesn't care if you've passed a Question or a
    // SecondaryQuestion, since they're both Questions.
  } else {
    // Get upset
  }
}