JavaScript Obj.isPrototypeOf(obj) method
The obj.isPrototypeOf(obj)
method in JavaScript is used to check if an object exists in the prototype chain of another object. It returns a boolean value indicating whether the specified object (obj
) is the prototype of another object.
Syntax:
Parameters:
prototypeObj
: The object that you want to check as a prototype.obj
: The object to be checked against the prototype.
Return Value:
true
: IfprototypeObj
is found in the prototype chain ofobj
.false
: IfprototypeObj
is not in the prototype chain ofobj
.
Key Features:
- Prototype Chain: This method is fundamental for understanding JavaScript’s prototype-based inheritance model. It helps determine the relationship between objects and their prototypes.
- Works with Any Object: It can be used with any type of object, including arrays, functions, and user-defined objects.
Example 1: Basic Usage
In this example, animal
is the prototype of dog
, so animal.isPrototypeOf(dog)
returns true
.
Example 2: Direct Prototype Check
Here, Person.prototype
is the prototype of the alice
instance, so the method returns true
.
Example 3: Checking Prototype in a Chain
In this example, parent
is the prototype of child
, and since all objects in JavaScript inherit from Object.prototype
, it also returns true
for that check.
Example 4: Non-Prototype Relationship
Here, since obj1
is not in the prototype chain of obj2
, the method returns false
.
Summary:
prototypeObj.isPrototypeOf(obj)
is a method that checks whether the specified object is in the prototype chain of another object.- It is essential for understanding the relationships between objects in JavaScript’s prototype-based inheritance model.
- This method helps clarify how objects inherit properties and methods, making it a valuable tool for developers working with JavaScript's object-oriented programming.