The isPrototypeOf() method in JavaScript is a powerful tool for determining if an object is in the prototype chain of another object. By calling this method on an object instance and passing in another object as an argument, you can quickly check if the object being called on is a prototype of the argument object. The method returns true
if the object is found in the prototype chain, and false
if it is not.
Let’s look at an example to understand how this works:
const Animal = {
isAnimal: true
}
const Mammal = Object.create(Animal)
Mammal.isMammal = true
Animal.isPrototypeOf(Mammal) // true
const dog = Object.create(Animal)
Object.setPrototypeOf(dog, Mammal)
Animal.isPrototypeOf(dog) // true
Mammal.isPrototypeOf(dog) // true
In the code above, we have defined an object Animal
with a single property isAnimal
. We then create a new object Mammal
using Object.create()
and set its prototype to Animal
. We also add an additional property isMammal
to Mammal
.
Next, we create a new object dog
using Object.create()
and set its prototype to Animal
using Object.setPrototypeOf()
. This means that dog
has both Animal
and Mammal
as part of its prototype chain.
When we call Animal.isPrototypeOf(Mammal)
, it returns true
because Animal
is indeed in Mammal
’s prototype chain. Similarly, when we call Animal.isPrototypeOf(dog)
and Mammal.isPrototypeOf(dog)
, both return true
since both Animal
and Mammal
are in dog
’s prototype chain.
Using the isPrototypeOf() method gives us a straightforward way to check if an object is a prototype of another object. It is particularly useful when working with inheritance and object hierarchies in JavaScript.
Tags: JavaScript, object prototype, isPrototypeOf()