Search code examples
javascriptinstanceofobject-create

Instanceof equivalent for Object.create and prototype chains


Consider such an object with a prototype chain:

var A = {};
var B = Object.create(A);
var C = Object.create(B);

How to check in runtime if C has A in its prototype chain?

instanceof doesn't fit as it's designed to work with constructor functions, which I'm not using here.


Solution

  • My answer will be short…

    You could use the isPrototypeOf method, which will be present in case your object inherits from the Object prototype, like your example.

    example:

    A.isPrototypeOf(C) // true
    B.isPrototypeOf(C) // true
    Array.prototype.isPrototypeOf(C) // false
    

    More info can be read here: Mozilla Developer Network: isPrototypeOf