3

Hello people of Stackoverflow! I have been going through the Mozilla Developer Network's JavaScript Guide and came across this function on the Details of the object model page:

The function is to check if an object is an instance of an object constructor:

function instanceOf(object, constructor) {
   while (object != null) {
      if (object == constructor.prototype)
         return true;
      if (typeof object == 'xml') {
        return constructor.prototype == XML.prototype;
      }
      object = object.__proto__;
   }
   return false;
}

My question is that, from the same page it says that is chris is an object of type Engineer then the following code returns true:

chris.__proto__ == Engineer.prototype;

However, in the above instanceOf function, it uses the following comparison expression to check if an object is an instance of a constructor function:

object == constructor.prototype

Should the expression not be:

object.__proto__ == constructor.prototype

Or am I missing a point here? Thank you all for your help and time in advance!

3
  • aha, thanks for that! I think I spent too much time straight on coding. Break time :P Commented Aug 25, 2012 at 14:51
  • You should probably accept the correct answer instead of just commenting. Commented Aug 25, 2012 at 15:07
  • @millimoose the answer was previously a comment itself. How do you think I'd accept that? Now I can and did. Commented Aug 26, 2012 at 9:06

3 Answers 3

5

You're missing the statement object = object.__proto__; at the bottom of the while loop... This traverses the prototype-chain. The object variable contains the current object from that chain for each step of the traversal.

Sign up to request clarification or add additional context in comments.

Comments

1

I know I'm a little late but the following is a snippet that should behave exactly like isInstanceOf

Object.prototype.instanceOf = function (type) {
    let proto = this.__proto__;
    while (proto) {
        if (proto.constructor && proto.constructor === type)
            return true;
        if (proto.__proto__)
            proto = proto.__proto__;
        else
            break;
    }
    return false;
};

console.log(Number(12).instanceOf(Number));  //true

Comments

0
function C() {}
function D() {}

var o = new C();

// true, because: Object.getPrototypeOf(o) === C.prototype
o instanceof C;

instanceOf will check the prototype for left side object with right side object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.