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!

Hirvesh
  • 7,636
  • 15
  • 59
  • 72

3 Answers3

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.

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
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
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.

Sagar Kharche
  • 2,577
  • 2
  • 24
  • 34