The isPrototypeOf()
method checks if an object exists in another object's prototype chain.
isPrototypeOf()
differs from the instanceof
operator. In the expression "object instanceof AFunction
", the object
prototype chain is checked against AFunction.prototype
, not against AFunction
itself.
prototypeObj.isPrototypeOf(object)
object
A Boolean
indicating whether the calling object has the specified object in its prototype chain.
The isPrototypeOf()
method allows you to check whether or not an object exists within another object's prototype chain.
This example demonstrates that Baz.prototype
, Bar.prototype
, Foo.prototype
and Object.prototype
exist in the prototype chain for object baz
:
function Foo() {} function Bar() {} function Baz() {} Bar.prototype = Object.create(Foo.prototype); Baz.prototype = Object.create(Bar.prototype); var baz = new Baz(); console.log(Baz.prototype.isPrototypeOf(baz)); // true console.log(Bar.prototype.isPrototypeOf(baz)); // true console.log(Foo.prototype.isPrototypeOf(baz)); // true console.log(Object.prototype.isPrototypeOf(baz)); // true
isPrototypeOf()
method, along with the instanceof
operator particularly comes in handy if you have code that can only function when dealing with objects descended from a specific prototype chain, e.g., to guarantee that certain methods or properties will be present on that object.
For example, check if baz
object descends from Foo.prototype
:
if (Foo.prototype.isPrototypeOf(baz)) { // do something safe }
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
© 2005–2017 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf