What's the difference between isPrototypeOf and instanceof in Javascript?

后端 未结 3 1458
梦毁少年i
梦毁少年i 2021-01-30 13:02

In some of my own older code, I use the following:

Object.prototype.instanceOf = function( iface )
{
 return iface.prototype.isPrototypeOf( this );
};

3条回答
  •  无人及你
    2021-01-30 13:27

    Yes, they do the same thing, both traverse up the prototype chain looking for an specific object in it.

    The difference between both is what they are, and how you use them, e.g. the isPrototypeOf is a function available on the Object.prototype object, it lets you test if an specific object is in the prototype chain of another, since this method is defined on Object.prototype, it is be available for all objects.

    instanceof is an operator and it expects two operands, an object and a Constructor function, it will test if the passed function prototype property exists on the chain of the object (via the [[HasInstance]](V) internal operation, available only in Function objects).

    For example:

    function A () {
      this.a = 1;
    }
    function B () {
      this.b = 2;
    }
    B.prototype = new A();
    B.prototype.constructor = B;
    
    function C () {
      this.c = 3;
    }
    C.prototype = new B();
    C.prototype.constructor = C;
    
    var c = new C();
    
    // instanceof expects a constructor function
    
    c instanceof A; // true
    c instanceof B; // true
    c instanceof C; // true
    
    // isPrototypeOf, can be used on any object
    A.prototype.isPrototypeOf(c); // true
    B.prototype.isPrototypeOf(c); // true
    C.prototype.isPrototypeOf(c); // true
    

提交回复
热议问题