JavaScript Object.isPrototypeOf()

The Object.isPrototypeOf() method checks if an object exists in another object's prototype chain.

Example


isPrototypeOf() syntax

The syntax of the isPrototypeOf() method is:

prototypeObj.isPrototypeOf(obj)

Here, prototypeObj refers to the object against which we want to compare our selected object's (obj) prototype.

Since isPrototypeOf() is a static method, we need to access the method using the class name, Object.


isPrototypeOf() Parameters

The isPrototypeOf() method takes in:

  • obj - the object whose prototype chain will be checked

isPrototypeOf() Return Value

The isPrototype() method returns:

  • true - if prototypeObj is the prototype of obj
  • false - if prototypeObj is not the prototype of obj, or if obj is not an object itself

Note: isPrototypeOf() differs from the instanceof operator as it checks the obj prototype chain against prototypeObj not prototypeObj.prototype.


Example 1: JavaScript Object.isPrototypeOf()

In the above example, we have used the isPrototype() method to check the prototypes of:

  • obj - an object
  • obj.toString - a function that returns a string representation of obj
  • [2, 4, 8] - an array of integers

Since Object.prototype is the root prototype of all objects, we get true as an output while checking Object.prototype against obj.

Similarly,

  • Function.prototype is the prototype of all functions, which includes obj.toString.
  • Function.prototype is the prototype of all arrays, including [2, 4, 8].

Example 2: isPrototypeOf() With a Custom Object

In the above example, we have created two objects: Animal and dog1. Notice that the dog1 object has been created using the Dog() constructor function.

Using the setPrototypeOf() method, we have set the prototype of all the objects created from the Dog() constructor function to that of Animal.

Hence, we get true as an output while checking whether the Animal object is a prototype of dog1.


Recommended Reading: